Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

c++ - Enable method based on boolean template parameter

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

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).

Is it possible to realize the desired behavior with enable_if?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...