dot dot dot dot dot dot - 26 days ago 17
C++ Question

Implement error message for trait specialization of class

How to implement an error message when the library user uses the wrong type for a template argument of a template class?

test.cpp (adapt from here)

#include <type_traits>
template <typename T, typename Enable = void>
class foo; // Sorry, foo<T> for non-integral type T has not been implemented.

template <typename T>
class foo<T, typename std::enable_if<std::is_integral<T>::value>::type>
{ };

int main()
{
foo<float> x;
}


The code does not compile, as expected. But I can't make the compiler show an error only when the user used the wrong type.

Error message of
g++ test.cpp


test.cpp: In function ‘int main()’:
test.cpp:11:13: error: aggregate ‘foo<float> x’ has incomplete type and cannot be defined
foo<float> x;


Problem: It doesn't print the error message that I want (
Sorry, foo<T> for non-integral type T has not been implemented.
)

Answer

static_assert will do the trick:

template <typename T, typename Enable = void>
class foo
{
    static_assert(sizeof(T) == 0, "Sorry, foo<T> for non-integral type T has not been implemented");
};

Demo

You need the sizeof(T) == 0 because the static_assert is always evaluated, and needs to depend on T otherwise it will always trigger, even for valid T.

Comments