我的代码是:
template<int s>
struct C{
typename std::enable_if<s == 1, int>::type
fun(){std::cout<<"fun1";}
typename std::enable_if<s == 2, int>::type
fun(){std::cout<<"fun2";}
};
int main() {
C<1> c;
c.fun();
}
编译器说:
error: functions that differ only in their return type cannot be overloaded
如果使用template<int t = s>
,我的编译器是g++ 4.1.2在函数之前,它会警告这是C++11特性。我想知道如何在不使用 C++11 的情况下解决这个问题?
最佳答案
如果您能够实现enable_if
特征,您可以按如下方式重新排列代码(最小的完整示例)以使其正常工作:
#include<type_traits>
#include<iostream>
struct C {
template<int s>
typename std::enable_if<s == 1, int>::type
fun() { std::cout<<"fun1"; }
template<int s>
typename std::enable_if<s == 2, int>::type
fun() { std::cout<<"fun2"; }
};
int main() {
C c;
c.fun<1>();
}
即使使用 C++11 功能,您的版本(与以下版本几乎相同)也无法工作,因为它不是名称 fun
的 SFINAE 解析。 :
#include<type_traits>
#include<iostream>
template<int s>
struct C {
typename std::enable_if<s == 1, int>::type
fun() { std::cout<<"fun1"; }
typename std::enable_if<s == 2, int>::type
fun() { std::cout<<"fun2"; }
};
int main() {
C<1> c;
c.fun();
}
如果您希望实例化该类,如 C<1>
,只是 SFINAE 不是这次的出路。
请注意s
在编译时就知道您决定使用模板类,因此您可以随时使用它。
它遵循一个可能的解决方案:
#include<type_traits>
#include<iostream>
template<int s>
struct C {
void fun() {
if(s == 1) {
std::cout<<"fun1";
} else if(s == 2) {
std::cout<<"fun2";
}
}
};
int main() {
C<1> c;
c.fun();
}
使用部分特化可以实现另一种解决方案,如下所示:
#include<type_traits>
#include<iostream>
template<int s>
struct C;
template<>
struct C<1> {
void fun() { std::cout<<"fun1"; }
};
template<>
struct C<2> {
void fun() { std::cout<<"fun2"; }
};
int main() {
C<1> c;
c.fun();
}
哪一种适合你主要取决于实际问题,所以我不能说,但至少现在你有几种解决方案可供选择。
关于c++ - 如何使用enable_if定义不同的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35619767/