I have an SFINAE test for checking if an class has a function. The test works correctly, but I get compiler errors when I try to use it in an if statement.
//SFINAE test for setInstanceKey()
template <typename K>
class HasSetInstanceKey
{
template <typename C>
static char test( typeof(&C::setInstanceKey) );
template <typename C>
static long test(...);
public:
enum { value = 1 == sizeof(test<K>(0)) };
};
I get “error: ‘class Node’ has no member named ‘setInstanceKey’” on the second line even though the else clause should be executing.
if ( 0 != HasSetInstanceKey<T>::value)
instance->setInstanceKey(instanceKey);
else
...
Is there a way to make this work?
Thanks.
Just because the if-branch is never entered doesn’t mean the code within the branch can be invalid. (Another way to think about it: you aren’t guaranteed anything about optimizations, yet your code would only be valid with a dead-branch optimization.)
What you do is shift the branch to a function. Typically you have a framework like this:
Then something like this:
It’s good practice to have to meta-functions inherit from the correct
bool_type, to ease use:So it just becomes: