对于像这样的小示例,如果T
是T
,我只想接受struct/class
,并拒绝诸如“int”,“char”,“bool”等内置类型。
template<typename T>
struct MyStruct
{
T t;
};
最佳答案
您正在从 std::is_class
header 中查找 <type_traits>
特性。哪一个
Checks whether
T
is a non-union class type. Provides the member constant value which is equal totrue
, ifT
is a class type (but not union). Otherwise, value is equal tofalse
.
例如,您可以使用
static_assert
作为模板类型T
,如下所示:#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更新
在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)
关于c++ - 如何检查模板参数是否为结构/类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63198504/