I saw the following example of enable_if for C++11:
struct is_64_bit
{
static const bool value = sizeof(void*) == 8;
};
enable_if<is_64_bit::value, void>::type
my_memcpy(void* target, const void* source, size_t n)
{
cout << "64 bit memcpy" << endl;
}
enable_if<!is_64_bit::value, void>::type
my_memcpy(void* target, const void* source, size_t n)
{
cout << "32 bit memcpy" << endl;
}
As I understand, depending on the system architecture, the “my_memcpy” function will be available either for 32 or 64 bit versions. But I’m getting the following error at compilation :
error: ‘type’ in ‘struct std::enable_if<false, void>’ does not name a type
I’m a bit confused because I thought only the 32 version should be available (I’m using Linux Fedora 32 bits).
Maybe is something wrong with this example? or Am I missing something?
Thanks.
The template
template< bool B, class T = void > struct enable_ifis specialized so that it only has atypedef typewhen the condition B istrue.Your compiler is correct. There is no typedef for
typeinstruct std::enable_if<false, void>. There is only a typedef instruct std::enable_if<true, void>.For more info look here.
So to fix your problem you need to make sure that the
enable_ifwhich has a B that evaluates tofalsenever gets compiled. You can achieve this with the help of SFINAE by makingmy_memcpya function template. The compiler will then not report an error when failing to compile the function template where B evaluates tofalseand will successfully compile and use the function where B evaluates totrue.