简体   繁体   English

如何检查模板参数是否为结构/类?

[英]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.对于像这样的小示例,我只想在Tstruct/class时接受T并拒绝内置类型,如“int”、“char”、“bool”等。

template<typename T>
struct MyStruct
{
   T t;
};

You are looking for std::is_class traits from <type_traits> header. Which您正在寻找来自<type_traits> header 的std::is_class特征。

Checks whether T is a non-union class type.检查T是否为非联合 class 类型。 Provides the member constant value which is equal to true , if T is a class type (but not union).如果T是 class 类型(但不是联合),则提供等于true的成员常量值。 Otherwise, value is equal to false .否则,值等于false


For instance, you can static_assert for the template type T like follows:例如,您可以为模板类型T进行static_assert ,如下所示:

#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.在 C++20 中,也可以使用std::is_class提供一个概念,如下所示。

#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 ) 见演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM