Kev*_*vin 6 c++ templates template-specialization
我遇到了模板专业化的问题.以下构建和运行,但我不确定它应该:
// template.h
template <typename T>
class interface{
public:
void doSomething();
};
// template.cpp
#include "template.h"
#include <iostream>
template <> void interface<int>::doSomething(){std::cout << "Did something\n";}
// main.cpp
#include "template.h"
int main(){
interface<int> instance;
instance.doSomething();
return 0;
};
g++ main.cpp template.cpp; ./a.out
Run Code Online (Sandbox Code Playgroud)
我的理解是所有编译单元都应该可以访问所有模板特化,而main.cpp则没有.如果我理解正确发生的事情,template.cpp中的特化也会实例化interface <int>,因此生成符号并且所有内容都很愉快地链接.但是,我很确定这属于不确定性的范畴,我不能指望它始终在任何地方工作.有人可以确认或否认我的怀疑吗?
谢谢!