假设您有以下模板方法:
class A
{
template<typename T>
void f(const T& t)
{
// do something with t.
}
};
现在,我想为除 T 之外的特定类实现 f() 的不同实现:
class A
{
template<typename T>
void f(const T& t)
{
// do something with t.
}
void f(const std::string& t)
{
// do something ELSE with t if T is std::string.
}
};
我知道我可以在模板方法上使用 std::enable_if<>(准确地说是一些“disable_if”),但我不喜欢这个解决方案,因为模板方法“知道”其他实现。
有没有更好的更正确的方法来做到这一点?
最佳答案
你展示的是重载,而不是特化。它应该像写的那样工作:你有什么问题?
无论如何,特化应该是这样的:
// Outside of the class definition:
template <>
inline void A::f<std::string>(const std::string& t) { ... }
请注意,此特化不再是模板函数,而是常规成员函数,只是名称很花哨。因此,它应该在 header 中声明并在源文件中定义,或者在 header 中使用 inline
关键字定义(我的示例显示的是后者)。
关于c++ - 对模板方法的特定特化使用不同签名的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27767784/