【发布时间】:2019-09-23 11:30:34
【问题描述】:
template<>std::string Add(std::string x ,std::string y)
{
return x.append(y);
}
std::string Add(std::string x ,std::string y)
{
return x.append(y);
}
如果我们可以使用函数重载来特化代码,为什么还需要模板特化?
【问题讨论】:
-
这真的取决于设计和用例,没有一个“真正”的答案。
-
当超载可以做到的时候,那就去超载,但这只是我个人的看法
-
如果您有 10 种类型需要完全相同的调用而两种不需要。你是在写 12 个重载还是 1 个模板和 2 个特化?我更喜欢模板
-
@deW1 我在询问这两个专业化。我们可以使用模板进行专业化std::string Add(std::string x ,std::string y) { return x.append(y ); } 但我们也可以专门使用函数重载 .right std::string Add(std::string x ,std::string y) { return x.append(y); }
-
@deW1 我认为您的(修辞?)问题的答案并不那么明显。如果我想阻止第 13 种类型作为参数传递,我更喜欢重载而不是模板 vodoo(尽管我仍然是一个 c++11 的人,其中 sfinae 仍然比现在更加神秘)
标签: c++ templates overloading template-specialization