Search code examples
c++templatesc++11template-specializationclass-template

Explicitly forbid a concrete class template specialisation


I have a class template:

template< typename ...bounded_types >
struct variant {};

But want to forbid empty list of bounded types, i.e. variant<> must be forbidden at compile time. I can do the following:

template<>
struct variant<>;

But it is not too clear: if my variant library contain a plenty of headers, then it is not evident, whether above specialization is not the forward declaration of a class, defined somewhere below. At my mind, ideal imaginary solution will be:

template<>
struct variant<> = delete;

This looks in greater extent explicitly, but sadly, in turn, forbidden by C++ syntax.

What is the most explicit way to satisfy the intentions described?


Solution

  • template<typename... bounded_types>
    struct variant {
        static_assert(sizeof...(bounded_types) > 0, "empty variant is illegal");
    };
    

    See how it fails: http://coliru.stacked-crooked.com/a/c08bee816d2bc36c
    See how it succeeds: http://coliru.stacked-crooked.com/a/b34ece864f770d24