-
SFINAE trouble
Okay, so I always fail at applying std::enable_if properly for some reason. So maybe someone here who is better at this can tell why this isn't working?
Code:
template<bool B>
struct Test
{
template<typename T = void>
std::enable_if_t<B> test1() { std::cout << "test1\n"; }
template<typename T = void>
std::enable_if_t<!B> test2() { std::cout << "test2\n"; }
};
int main()
{
Test<true> a;
Test<false> b;
}
Code:
Error 1 error C2039: 'type' : is not a member of 'std::enable_if<false,void>'
Error 2 error C2061: syntax error : identifier 'type'
Error 3 error C2988: unrecognizable template declaration/definition
Error 4 error C2059: syntax error : '<end Parse>'
Error 5 error C2143: syntax error : missing ';' before '}'
Error 6 error C2238: unexpected token(s) preceding ';'
Error 7 error C2061: syntax error : identifier 'type'
Error 8 error C2988: unrecognizable template declaration/definition
Error 9 error C2059: syntax error : '<end Parse>'
Error 10 error C2334: unexpected token(s) preceding '{'; skipping apparent function body
-
Oh! I recall now. The enable_if construct has to depend on a template parameter. So if we do:
Code:
template<bool B>
struct Test
{
template<bool B2 = B>
std::enable_if_t<B2> test1() { std::cout << "test1\n"; }
template<bool B2 = B>
std::enable_if_t<!B2> test2() { std::cout << "test2\n"; }
};
int main()
{
Test<true> a;
Test<false> b;
}
Then it starts working. I should keep this for future reference.
-
I think you want to do
Code:
template<bool B>
struct Test
{
template<bool B2=B>
typename std::enable_if_t<B2>::type test1() { std::cout << "test1\n"; }
template<bool B2=B>
typename std::enable_if_t<!B2>::type test2() { std::cout << "test2\n"; }
};
enable_if::type will only be defined if the first template argument is true. You can also pass in a second template parameter, the typename that ::type should be typedefed to, which defaults to void.
-
std::enable_if_t<B> == typename std::enable_if<B>::type
-
Ah missed the _t, serves me for reading code on an empty stomach...