只有一个模板专业化有用

Is having only a single template specialisation useful?

本文关键字:专业化 有用 有一个      更新时间:2023-10-16

我想知道以下方法之间的主要区别是什么。如果定义了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)并不是真正的模板专业化,因为它在定义之前错过了模板&lt;>。因此,编译器将其视为完全定义的功能,而不是使用混凝土类型生成的模板。这意味着只要编译器可以与参数列表匹配。

始终使用此功能。

尽管您使用指令对您的名称空间的不必要污染之类的东西,如果您打算使用to_string

之类的名称,这尤其很奇怪。

模板功能自动推论其模板参数。因此,以下是绝对有效的:

int main(int argc, const char * argv[]) {
    to_string(eColor::Red);
    to_string("Hey");
    to_string(42);
    return 0;
}

因此,如果您真正打算将您的功能用于一种专用类型的功能,则您的一些非常有趣的错误消息或更糟糕的是,没有错误消息与不需要的行为相结合。

功能版本至少可以防止某些错误情况。(尽管存在隐式转换,但它仍然会接受42。