barteks2x
barteks2x

Reputation: 1355

Is it possible to write C++ template that won't accept any type?

I'm curious if it's possible to write such C++ template for which it's impossible to create a class/type it will accept (compile without errors). If it is possible, what it could be?

Upvotes: 0

Views: 81

Answers (2)

R Sahu
R Sahu

Reputation: 206667

One way you can do that is provide a forward declaration of the class template only. One example of such a class template that I have used in the past is to print the size of a type as a compiler error.

template <size_t> struct PrintSize;

PrintSize<sizeof(int)> a;

When you compile that code, you will be able to tell the size of int from the error message issued by the compiler.

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119382

Sure. For example:

template <typename T>
struct S {
    static_assert(std::is_class<T>::value, "T must be a class");
    static_assert(!std::is_class<T>::value, "T must not be a class");
};

However, such a template is automatically ill-formed NDR.

If no valid specialization can be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic required.

([temp.res]/8)

Upvotes: 2

Related Questions