【发布时间】:2019-01-15 14:23:08
【问题描述】:
以下代码在使用 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 专业化(声明或定义)的可见性。
如果没有,这是否包含在标准中或仅仅是编译器实现细节?
【问题讨论】:
标签: c++ visual-c++ template-specialization