[英]specialization of member function of templated class
那里:
以下代码的结果是什么?
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<int>::print()
有两种实现-从类模板定义和foo.cxx中的非内联定义获得的内联定义。 编译器可以自由选择。
不需要编译器将其诊断为问题。 它们中的许多(显然包括g ++和MSVC)都选择了用于定义类模板及其成员函数的途径。
为了确保两个编译器都选择foo.cxx中的实现,请在foo.h中声明该函数。
#include <iostream>
template<class _Tp>
struct Foo
{
void print() { std::cout << "foo\n"; }
};
template<> void Foo<int>::print();
这很有趣。 我知道模板是在编译时而不是链接时解释的。 因此,我认为,专业化模板应在每个cpp文件中实现。 您的g ++版本是什么?
如果foo.h如下所示,则两个编译器将产生相同的结果。 但是我不知道为什么。
#include <iostream>
template<class _Tp>
struct Foo
{
void print();
};
template<class _Tp>
void Foo<_Tp>::print()
{
std::cout << "foo\n";
}
template<> void Foo<int>::print();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.