I can't understand the second scenario presented here. It says:
•Scenario 2: Adding a function parameter that has a default argument:
template <your_stuff> your_return_type_if_present
yourfunction(args, enable_if_t<your condition, FOO> = BAR) {
// ...
}
Scenario 2 leaves the parameter unnamed. You could say
::type Dummy = BAR
, but the name Dummy is irrelevant, and giving it a name is likely to trigger an unreferenced parameter warning. You have to choose aFOO
function parameter type andBAR
default argument. You could sayint
and0
, but then users of your code could accidentally pass to the function an extra integer that would be ignored. Instead, we recommend that you usevoid **
and either0
ornullptr
because almost nothing is convertible tovoid **
:
template <your_stuff> your_return_type_if_present
yourfunction(args, typename enable_if<your_condition, void **>::type=nullptr) {
// ...
}
If scenario 2 leaves the parameter unnamed then in what can it be used?
Is there a way to make a code like this work with enable_if
?
enum otype {oadd,omull};
template<otype o>
int add(int num1, std::enable_if<o == oadd, int>::type int= num2)
{
if (o == omull) return num1 * num1;
if (o == oadd ) return num1 + num2;
}
enable_if
examples (if it helps):
For functions with non-void return type:
For single condition:
template <template T, typename std::enable_if<!std::is_same<T,std::string>::value>::type* = nullptr >
T func(T x){}
For multiple condition:
template <template T, typename std::enable_if<!std::is_same<T,std::string>::value &&!std::is_same<T,int>::value>::type* = nullptr >
T func(T x){}
For single condition:
template <template T>
typename std::enable_if<!std::is_same<T,std::string>::value>::type
func(T x){}
For multiple condition:
template <template T>
typename std::enable_if<!std::is_same<T,std::string>::value &&!std::is_same<T,int>::value>::type
func(T x){}
Don't forget to include #include <type_traits>