在那里:
以下代码的结果是什么?
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;
}结果是不同的:
我想得到第二个结果,不管编译器是什么。另外,我应该做些什么来实现呢?如果可能的话,你能给我解释一下基本的标准或机制吗?谢谢!
发布于 2016-10-09 03:46:48
您的程序有未定义的行为。
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();发布于 2016-10-09 04:54:28
这是利息。我知道模板是在编译时解释的,而不是链接时间。因此,在我看来,专门化模板应该在每个cpp文件中实现。你的g++版本是什么?
发布于 2016-10-09 05:25:06
如果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();https://stackoverflow.com/questions/39939722
复制相似问题