Dependent template parameters
My templated function has two template parameters(int m
and int n
). The function returns a class Foo<int r>
, where I want r=m+n
.
In foo.h I have:
template<int m> cla开发者_开发知识库ss Foo {};
template<int m, int n>
Foo<m+n> myFunc(const Foo<m> &a, const Foo<n> &b);
In foo.cpp I have:
Foo<m+n> myFunc(const Foo<m> &a, const Foo<n> &b)
{
return Foo<m+n>();
}
And finally in main.cpp:
#include "foo.h"
int main()
{
myFunc(Foo<2>(), Foo<3>());
}
If I try this, I get a linker error.:
"undefined reference to `Foo<(2)+(2)> myFunc(Foo<2> const&, Foo<2> const&)'
EDIT: Edited to include complete code. Maybe less clear but preferred by some.
You are probably putting the function body code in the wrong place. With (non-specialised) template functions, you generally want to put the whole function body in the header file and not the source file, otherwise the compiler cannot generate the code for that function when it is called.
From what little you provide, the error indicates that though you've declared the function, you've not provided an implementation anywhere that the linker can see.
That's because you haven't defined the function or the definition is not visible to the compiler at the point of instantiation. If you write a function body, it works:
template <int> class Foo {};
template<int m, int n>
Foo<m+n> myFunc(const Foo<m> &a, const Foo<n> &b) {} // NOTE: Body.
int main () {
myFunc (Foo<1>(), Foo<2>());
}
(sidenote: post complete code next time, please)
精彩评论