Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C++ std::enable_if with a normal function?

Tags:

c++

templates

let's say I have an enumeration:

typedef enum {
  Val1,
  Val2,
  Val3,
  Val4
} vals;

And a function check(vals x) which returns a boolean indicating whether the val is in a specific subset of values in vals.

bool check(vals x) {
  switch(x) {
  case Val1:
  case Val3:
    return true;
  }
  return false;
}

I want to use this function as a condition for the enable_if (the function, as you can see, it's not a function depending on the runtime), to let the users use only those values with the class template.

class MyClass<vals v> {

}

PS: I need the template to make specializations for a method of the class, depending on the template value.

like image 245
NoImaginationGuy Avatar asked Dec 24 '22 05:12

NoImaginationGuy


1 Answers

In C++14, just declare the function constexpr and keep the implementation as is.

In C+11 you need to change it to a single return statement:

constexpr bool check(vals x) {
    return x == Val1 || x == Val3;
}
like image 79
n. 1.8e9-where's-my-share m. Avatar answered Jan 08 '23 00:01

n. 1.8e9-where's-my-share m.