单独定义模板类的模板成员
Defining a Template Member of a Template Class separately from the Declaration
#include <cstdlib>
template<class A> struct Foo
{
template<class B> static bool Bar();
};
template<class B> template<class A> bool Foo<A>::Bar<B>()
{
return true;
}
int main()
{
bool b = Foo<int>::Bar<long>();
b;
}
这会导致链接器错误:
main.obj : error LNK2019: unresolved external symbol "public: static bool __cdecl Foo<int>::Bar<long>(void)" (??$Bar@J@?$Foo@H@@SA_NXZ) referenced in function main
我需要在类模板声明之外定义这个成员函数。换句话说,我不能这样做:
#include <cstdlib>
template<class A> struct Foo
{
template<class B> static bool Bar()
{
return true;
}
};
int main()
{
bool b = Foo<int>::Bar<long>();
b;
}
我错过了什么?如何定义这个成员函数模板?需要什么语法?
注意:我正在使用MSVC 2008,以防相关。
编辑我尝试的第一件事是颠倒template<class A>
和template<class B>
的顺序:
#include <cstdlib>
template<class A> struct Foo
{
template<class B> static bool Bar();
};
template<class A> template<class B> bool Foo<A>::Bar<B>()
{
return true;
}
int main()
{
bool b = Foo<int>::Bar<long>();
b;
}
这导致编译器错误:
.main.cpp(11) : error C2768: 'Foo<A>::Bar' : illegal use of explicit template arguments
在Bar
函数定义的右括号上
把template<class B> template<class A>
的顺序倒过来。第二个是"内部的",与成员声明一起使用。看到§14.5.2/1 .
同样,正如John指出的,从Bar<B>
中删除参数列表。
// "outer" template: this parameter gets substituted to create "inner" template
template< class A >
// "inner" template stands alone after "outer" substitution
template< class B >
bool
// This will just be a class name after "outer" substitution.
foo<A>
// This has usual function template syntax
:: Bar() {
这个适合我:
template<class A>
template<class B>
bool Foo<A>::Bar()
{
return true;
}
编写两个template
说明符的顺序很重要(首先是外部模板)。此外,如果您实际将<B>
放在函数模板的名称上,至少有一个编译器(GCC)认为您试图部分专门化函数Bar
,这是不可能的。
相关文章:
- 类模板的成员功能的定义在单独的TU中完全专业化
- 使用模板参数还包括 constexpr 成员函数enable_if单独定义和声明模板成员函数
- 单独构造结构的数据成员合法吗
- 好友成员函数可以在单独的文件中使用吗?
- 单独库中的类成员函数定义和链接依赖项
- enable_if具有单独定义的类成员函数
- 如何在单独文件中定义的成员函数中使用成员变量
- 如何为同一类对象的成员函数保留单独的变量副本?
- 在单独的线程中使用参数启动成员函数
- 在单独的线程中运行成员功能
- 无法从单独的.cpp使用模板化成员编译/链接类
- 如何使用模板化的外部类单独定义嵌套类成员函数
- C++ - 通过 getter 函数在单独的类中从对象指针映射访问成员函数
- 从单独函数中的结构中检索数组成员
- 在单独的库中使用 CRTP 进行静态成员初始化
- C++:链接器错误:未定义的引用仅指向在单独文件中定义的一个特定类成员
- 防止单独调用成员函数
- 单独声明和定义模板函数的专门化:成员函数和非成员函数的不同行为
- 我们是否仍然需要单独定义静态成员,即使它们是在类定义中初始化的
- 是否有任何方法来检测重载成员函数的名称单独?(不检测名称)