C++ 模板 : separation of definition and implementation using template arguments

标签 c++ templates visual-c++ c++11

老实说,我真的不知道如何命名这个问题。我将只显示不起作用的代码:

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/

相关文章:

c++ - unique_ptr(std::nullptr_t) 和模板

c++ - 类的 unique_copy 无法识别运算符<

c++ - 错误 : 'T' is not a template

c++ - 调用模板显式实例化时如何开启自动匹配?

visual-studio - Visual Studio/C++ : How to turn off certain first-chance exception debug messages?

c++ - 有没有一种简单的方法可以在初始化后填充二维数组?

c++ - 错误 'class HotelRoom' 没有名为 'menu' 的成员,即使它存在

c++ - 如果参数类型可转换,则将函数类型转换为不同

c++ - 列表排序不正确

visual-studio-2010 - VS 2010 C++ 智能感知