以下代码在使用 Clang 的 macOS 上编译和运行正确,但在使用 MSVC 2017 的 Windows 上却没有。
// File: toString.h
#include <string>
template<typename T>
const std::string toString(T){return "";}
// File: toString.cpp
#include "toString.h"
template <>
const std::string toString<int>(int value){
return std::to_string(value);
}
// File: main.cpp
#include <iostream>
#include "toString.h"
int main() {
// specialized
std::cout <<"int: "<< toString(1) << std::endl;
// not specialized
std::cout <<"double: "<< toString(1.0) << std::endl;
return 0;
}
// Expected output:
// int: 1
// double:
它在链接器处失败,因为函数是隐式实例化的,而不是链接到 int 特化,导致重复符号。
如果模板的默认实现被删除,那么打印的double行将失败,因为没有符号可以链接它。
我的问题是是否有任何方法可以在使用 MSVC 的 Windows 上实现相同的结果,而 main.cpp 没有任何 toString 专业化(声明或定义)的可见性。
如果没有,这是标准涵盖的还是仅仅是编译器实现细节?