基于布尔模板参数的启用方法 [英] Enable method based on boolean template parameter

查看:52
本文介绍了基于布尔模板参数的启用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于布尔模板参数实现私有功能.像这样的东西:

I want to implement a private function based on a boolean template parameter. Something like that:

#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,类型名std :: enable_if :: type * = 0).

But the program above does not compile: error: no type named 'type' in 'struct std::enable_if' void funInternal(int a, typename std::enable_if::type* = 0).

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

Is it possible to realize the desired behavior with enable_if?

推荐答案

以下是解决方案的改编版( @chris 似乎可以满足您的需求.

The following is an adaptation of the solution (http://coliru.stacked-crooked.com/a/480dd15245cdbb6f) provided by @chris in the comments, which seems to meet your needs.

#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;
}

这篇关于基于布尔模板参数的启用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆