我想知道以下方法之间的主要区别是什么。如果定义了 std::to_string
,是否存在两者之一会导致问题的情况?
include <string>
using namespace std;
enum class eColor
{
Red
};
void to_string(eColor color)
{
}
template<typename C = eColor)
void to_string(C color)
{
}
int main()
{
to_string(eColor::Red); // assume only one of the above is defined
return 0;
}
在某些情况下应该首选上述其中一项吗?
最佳答案
你的函数 to_string(eColor color) 并不是真正的模板特化,因为它在定义之前错过了 template<> 。所以编译器将其视为一个完全定义的函数,而不是一个要用具体类型生成的模板。这意味着只要编译器可以匹配参数列表,就会始终使用此函数。
关于c++ - 只有一个模板特化有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46236525/