Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a template parameter is a struct/class?

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;
};
like image 589
A. K. Avatar asked Jul 31 '20 20:07

A. K.


People also ask

Can a struct be a template?

You can template a struct as well as a class. However you can't template a typedef. So template<typename T> struct array {...}; works, but template<typename T> typedef struct {...} array; does not.

Can we use template in struct in C++?

A C++ template creates an algorithm independent of the type of data employed. So, the same algorithm, with many occurrences of the same type, can use different types at different executions. The entities of variable, function, struct, and class can have templates.

What are non-type parameters for templates?

A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.

Is template a data structure?

When a data structure is used only as a format for other data structures, it is referred to as a data structure template. The new data structure is always a qualified data structure that includes all of the subfields from the original data structure.


1 Answers

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)


c++20 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)

like image 152
JeJo Avatar answered Oct 20 '22 16:10

JeJo