c++ - 如何使用enable_if定义不同的成员函数?

标签 c++ templates g++ traits

我的代码是:

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/

相关文章:

c++ - 特化一个模板类,使其在一种情况下表现得像一个 float

c++ - 修复对 dlopen() 和 dlcose() 的 undefined reference

c++ - 链接不同版本的共享库

c++ - 如何用多态实现数据局部性?

c++ - 为什么大小为 2 的幂的数组速度较慢?为什么我会获得 -rdynamic 性能?

c++ - 如何使用特征来访问编译时 const 值?

c++ - boost::remove_pointer 是如何工作的?

c++ - 使用gcc在C中链接C++静态库

c++ - 如果将 Memoization 添加到 Recursion,则错误的解决方案

c++ - C++03 throw() 说明符 C++11 noexcept 之间的区别