我的模板化函数具有两个模板参数(int mint n)。该函数返回一个Foo<int r>类,我想要r=m+n

在foo.h中,我有:

template<int m> class Foo {};
template<int m, int n>
Foo<m+n> myFunc(const Foo<m> &a, const Foo<n> &b);

在foo.cpp中,我有:
Foo<m+n> myFunc(const Foo<m> &a, const Foo<n> &b)
{
    return Foo<m+n>();
}

最后在main.cpp中:
#include "foo.h"
int main()
{
    myFunc(Foo<2>(), Foo<3>());
}

如果尝试此操作,则会收到链接器错误:
 "undefined reference to `Foo<(2)+(2)> myFunc(Foo<2> const&, Foo<2> const&)'

编辑:编辑以包括完整的代码。也许不太清楚,但有些人喜欢。

最佳答案

您可能将函数主体代码放在错误的位置。对于(非专用)模板函数,通常希望将整个函数主体放在头文件中,而不是源文件中,否则,编译器在调用该函数时无法为该函数生成代码。

10-06 10:39
查看更多