Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is_base_of fails when both are just plain char type

Tags:

c++

Do you see why the static_assert fail:

template <typename T>
void 
foo(const T &c)
{

    static_assert(std::is_base_of<T, char>::value, "T must be char");  // Fails !

}

int main()
{
    char c = 'a';

    foo<char>(c);

    return 0;
}

I swapped T and "char", still fails.

like image 932
my_question Avatar asked Jun 02 '14 03:06

my_question


2 Answers

You might want to consider adding additional checks:

template <typename T> void foo(const T &c) 
{
    static_assert(
            std::is_base_of<T, char>::value || std::is_same<T, char>::value, 
            "T must be char");

}

But if you are only concerned about chars, then you might as well do:

static_assert(std::is_same<T, char>::value, "T must be char");

Also consider is_fundamental, and is_convertible for more complex assertions.

like image 100
perreal Avatar answered Nov 14 '22 21:11

perreal


The documentation for std::is_base_of states:

If Derived is derived from Base or if both are the same non-union class, provides the member constant value equal to true. Otherwise value is false.

But char is not a class : it is a primitive type, so this is the expected result.

like image 35
quantdev Avatar answered Nov 14 '22 21:11

quantdev