[英]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.对于像这样的小示例,我只想在T
是struct/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 totrue
, ifT
is a class type (but not union).如果T
是 class 类型(但不是联合),则提供等于true
的成员常量值。 Otherwise, value is equal tofalse
.否则,值等于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 ) (见演示)
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.