5

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.

Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
my_question
  • 3,075
  • 2
  • 27
  • 44

2 Answers2

5

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.

perreal
  • 94,503
  • 21
  • 155
  • 181
4

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.

quantdev
  • 23,517
  • 5
  • 55
  • 88