use*_*652 2 c++ templates overloading c++11
我有以下课程:
template <typename T>
struct Foo {
void bar(double val);
void bar(T val);
T m_val;
};
Run Code Online (Sandbox Code Playgroud)
现在问题是如果我实例化一个类型的对象Foo<double>,我得到两个具有相同签名的重载函数.
它有什么办法吗?
我的问题是我确实需要处理特殊val类型的情况double.此外,bar非双重类型的参数没有共同的超类.
另一个方法是禁用SFINAE的功能:
#include <iostream>
#include <string>
#include <vector>
template <typename T>
struct Foo {
void bar(double val){
std::cout << "bar(double)\n";
}
template<class Y=T>
typename std::enable_if<!std::is_same<Y, double>::value>::type
bar(T val){
std::cout << "bar(T)\n";
}
T m_val;
};
int main()
{
Foo<double> dd;
dd.bar(1.0);
Foo<std::string> dd2;
dd2.bar("asds");
dd2.bar(1.0);
}
Run Code Online (Sandbox Code Playgroud)
[编辑]
正如WF在评论中指出的那样,你在这里不需要enable_if,使bar(T)模板成员函数足以消除它的歧义:
template<int=0>
void bar(T val){
std::cout << "bar(T)\n";
}
Run Code Online (Sandbox Code Playgroud)
您可以创建模板专业化.在模板类或函数的特化中,您可以为特定类型定义唯一行为.例如:
template<typename T>
struct Foo {
void bar(T);
T m_val;
}
template <>
struct Foo<double> {
void bar(double);
double m_val;
};
Run Code Online (Sandbox Code Playgroud)
或者你可以只为这种情况专门设计一个函数:
template <>
void Foo<double>::bar(double);
Run Code Online (Sandbox Code Playgroud)
现在当你做以下时:
int main() {
Foo<double> ob1;
Foo<int> obj2;
obj1.bar(1,3);
obj2.bar(45);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
obj1.bar从专业化调用bar函数.