Monday, October 28, 2019

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 

using namespace std;

template

class Aggregator {
public:
void fun(int a) {
funInternal(a);
}

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


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

int main()
{
Aggregator a1;
Aggregator 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?


Answer



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 

template
class Aggregator
{
public:

void fun(int a)
{
funInternal(a);
}

private:
template
void funInternal(typename std::enable_if::type a)
{
std::cout << "Feature is enabled!" << std::endl;

}

template
void funInternal(typename std::enable_if::type a)
{
std::cout << "Feature is disabled!" << std::endl;
}
};

int main()

{
Aggregator a1;
Aggregator a2;

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

return 0;
}


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...