there:模板类成员函数的专门化
以下代码的结果是什么?
foo.h中
#include <iostream>
template<class _Tp>
struct Foo
{
void print() { std::cout << "foo\n"; }
};
foo.cxx
#include "foo.h"
template<>
void Foo<int>::print()
{
std::cout << "foo<int>\n";
}
main.cxx
#include "foo.h"
int main()
{
Foo<double>().print();
Foo<int>().print();
return 0;
}
结果是不同的:
时MSVC遵守,
foo foo
当G ++编译,
foo foo<int>
我想获得第二个结果无论编译器。我应该额外做些什么来实现?如果可能,你会给我一个关于基本标准或机制的解释。谢谢!
“以下代码的结果”是foo.cxx中的编译错误,因为它不包含有效的C++代码。 –
我改变了错误类型:void Foo :: void print() - > void Foo :: print()你会再次看到,谢谢。 –
您只需要在头文件中声明特殊化,以便它在所有翻译单元中可见。添加一个'template <> void Foo :: print();'声明到头文件。 –