只有一个模板专业化有用
Is having only a single template specialisation useful?
我想知道以下方法之间的主要区别是什么。如果定义了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。
相关文章:
- 如何使用默认参数等选择模板专业化
- 模板化建造师专业化
- 类模板的成员功能的定义在单独的TU中完全专业化
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 部分专业化和嵌套模板
- 模板专业化可以进入我的.cpp吗?
- 其中降频广播实际上是有用的
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- 部分专业化和对标准::void_t<>的需求
- "专业化不参与超载"
- 特定好友功能专业化
- 是否可以混合使用SFINAE和模板专业化?
- 既然我们有内联变量,extern const 还有用吗?
- 为什么在班级专业化上会出现错误?
- enable_if如何帮助选择类模板的专业化?
- std::initializer_list可以专业化吗?
- 派生类中纯虚拟基方法的专业化
- 函子还有更有用的用例吗?
- "expected a '>'"类模板专业化?
- 只有一个模板专业化有用