基于布尔模板参数的启用方法

Enable method based on boolean template parameter

我想实现一个基于布尔模板参数的私有函数。类似的东西:

#include <iostream>

using namespace std;

template <bool is_enabled = true>
class Aggregator {
public:
    void fun(int a) {
        funInternal(a);
    }

private:
    void funInternal(int a, typename std::enable_if<is_enabled>::type* = 0) {
        std::cout << "Feature is enabled!" << std::endl;
    }

    void funInternal(int a, typename std::enable_if<!is_enabled>::type* = 0) {
        std::cout << "Feature is disabled!" << std::endl;
    }
};

int main()
{
   Aggregator<true> a1;
   Aggregator<false> a2;

   a1.fun(5);
   a2.fun(5);

   return 0;
}

但上面的程序无法编译:错误:'struct std::enable_if' 中没有名为 'type' 的类型 void funInternal(int a, typename std::enable_if::type* = 0).

是否可以通过 enable_if 实现所需的行为?

下面是改编的解决方案(http://coliru.stacked-crooked.com/a/480dd15245cdbb6f) provided by @chris在评论里,好像能满足你的需求。

#include <iostream>

template<bool is_enabled = true>
class Aggregator
{
public:
    void fun(int a)
    {
        funInternal(a);
    }

private:
    template<bool enabled = is_enabled>
    void funInternal(typename std::enable_if<enabled, int>::type a)
    {
        std::cout << "Feature is enabled!" << std::endl;
    }

    template<bool enabled = is_enabled>
    void funInternal(typename std::enable_if<!enabled, int>::type a)
    {
        std::cout << "Feature is disabled!" << std::endl;
    }
};

int main()
{
    Aggregator<true> a1;
    Aggregator<false> a2;

    a1.fun(5);
    a2.fun(5);

    return 0;
}