0

To be honest, I do not really know how to name that problem. I'll just show the code that is not working:

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;
}

I'd like to separate definition from implementation to avoid cyclic dependency issues. Separation is done in header files only, I don't want to put template code into cpp files. Using pointers is no option in that case. Refactoring has been considered but is not a real option, either.

Implementing foo::f without a parameter that has template parameters itself is working fine. I do not really get the problem with that parameter, though.

Code should work using gcc 4.7 and (even more important) Visual Studio 2010. C++11 is ok as long as supported by the platforms mentioned.

Solutions, workarounds as well as theoretical explanations why I'm doing something completly wrong will be highly appreciated. TIA.

4

4 回答 4

7
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){

}

请注意,这里的顺序很重要。

于 2012-06-18T12:02:19.837 回答
5

这是正确的语法:

template<int SIZE>
template<int X>
void foo<SIZE>::f(bar<X> b){

}

否则,您会说这foo是一个带有 2 个模板参数的类模板。

于 2012-06-18T12:01:56.947 回答
4

有两个级别的模板,您必须分别指定它们

template<int SIZE>
template<int X>
void foo<SIZE>::f(bar<X> b){  }
于 2012-06-18T12:03:13.310 回答
0

循环依赖是你的主要问题。你真的需要它们吗?尝试以一种依赖关系形成有向无环图的方式来解决您的问题,而且通常情况下,您最终会得到一个更好的解决方案。

如果你不能打破循环依赖,那么也许你应该重新考虑这两个模板是否应该在不同的组件中(在这种情况下是标题),因为如果没有另一个,这两个模板似乎都不有效。

于 2012-06-18T12:04:05.143 回答