c++ - 如何让成员函数实现依赖于类的模板参数?

标签 c++ c++11 enable-if

这是我最好的尝试:

#include <iostream>

template <bool EnableSomething = false>
class MyClass
{
    typename std::enable_if< EnableSomething >::type
        something(int& x)
    {
        x += 1; //do something
    }

    typename std::enable_if< !EnableSomething >::type
        something(int& x)
    {
        // do nothing, should be optimized away
    }

public:
    void Process()
    {
        int x = 0;
        something(x);
        std::cout << "Enabled: " << EnableSomething << ".  x = " << x << std::endl;
    }
};

int main()
{
    MyClass<true> yes;
    MyClass<false> no;
    yes.Process();
    no.Process();
    return 0;
}

编译器说: tester.cpp(12): error C2039: 'type': is not a member of 'std::enable_if<false,_Ty>'

最佳答案

使用从父模板中获取的默认参数制作常规模板:

template<bool x_enabled = EnableSomething> 
typename std::enable_if< x_enabled >::type
something(int& x)
{
    x += 1; //do something
}

template<bool x_enabled = EnableSomething> 
typename std::enable_if< !x_enabled >::type
something(int&)
{
    // do nothing, should be optimized away
}

使用 c++17 事情变得更简单:

void
something(int& x)
{
    if constexpr(EnableSomething)
    {
        x += 1; //do something
    }
}

关于c++ - 如何让成员函数实现依赖于类的模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49498177/

相关文章:

c++ - enable_if 和自动返回类型?

c++ - 为什么绑定(bind)到三元的 const 引用会生成拷贝?

c++ - 将 ATL::CString 转换为 std::vector<unsigned char>

c++ - regex_match 给出意想不到的结果

c++ - 链接器如何找到正确的库?

c++ - C++ 类的构造函数中的线程池被杀死

c++ - 基于表达式的std::enable_if使用静态constexpr成员函数

c++ - 我可以将enable_if替换为decltype吗

c++ - 二值图像数据上的 CImg

c++ - 经典 C++ 中的数据文件处理(很像 C)