6

For a small example like this, I want to only accept T if T is a struct/class and reject builtin types like 'int', 'char', 'bool' etc.

template<typename T>
struct MyStruct
{
   T t;
};
JeJo
  • 30,635
  • 6
  • 49
  • 88
A. K.
  • 34,395
  • 15
  • 52
  • 89

1 Answers1

12

You are looking for std::is_class traits from <type_traits> header. Which

Checks whether T is a non-union class type. Provides the member constant value which is equal to true, if T is a class type (but not union). Otherwise, value is equal to false.


For instance, you can static_assert for the template type T like follows:

#include <type_traits> // std::is_class

template<typename T>
struct MyStruct
{
   static_assert(std::is_class<T>::value, " T must be struct/class type!");
   T t;
};

(See a demo)


concept Updates

In C++20, one can provide a concept using std::is_class as follows too.

#include <type_traits> // std::is_class

template <class T> // concept
concept is_class = std::is_class<T>::value;

template<is_class T> // use the concept
struct MyStruct
{
   T t;
};

(See a demo)

JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 1
    [And, yes, this works for "structs" too; and, no, there shouldn't be a separate trait for it](https://stackoverflow.com/a/34108140/4386278) (because "structs" don't exist) – Asteroids With Wings Jul 31 '20 at 20:37