老实说,我真的不知道如何命名这个问题。我将只显示不起作用的代码:
template<int SIZE>
struct bar{
};
template<int SIZE>
struct foo{
template<int X>
void f(bar<X> b);
};
template<int SIZE, int X>
void foo<SIZE>::f(bar<X> b){
}
int main(){
foo<1> f;
bar<2> b;
}
我想将定义与实现分开以避免循环依赖问题。分离仅在头文件中完成,我不想将模板代码放入 cpp 文件中。在这种情况下,使用指针是不可行的。重构已被考虑,但也不是一个真正的选择。
在没有模板参数的情况下实现 foo::f 本身工作正常。不过,我并没有真正理解该参数的问题。
代码应该可以使用 gcc 4.7 和(甚至更重要的)Visual Studio 2010。只要所提到的平台支持,C++11 就可以。
解决方案、解决方法以及为什么我做的事情完全错误的理论解释将受到高度赞赏。 TIA。
最佳答案
template<int SIZE, int X> //problem : what is what here?
void foo<SIZE>::f(bar<X> b){
}
这是错误的语法。
正确的语法是使用 template
两次:
template<int SIZE> //for the class template
template<int X> //for the member function template
void foo<SIZE>::f(bar<X> b){
}
请注意,这里的顺序很重要。
关于C++ 模板 : separation of definition and implementation using template arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11082370/