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

标签 c++ c++11 templates c++14 class-template

对于像这样的小示例,如果TT,我只想接受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 to true, if T is a class type (but not union). Otherwise, value is equal to false.



例如,您可以使用 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)

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/

相关文章:

c++ - C++ 的 C 包装器

c++ - 在 OS X Mavericks 中从 C++ 链接 C

c++ - 传递带有默认值的函数作为忽略它们的参数

c++ - 什么样的值是模板参数?我能(不能)用它们做什么?

C++ 可变参数模板

c++ - 设计应用程序以支持配置更改而无需重新启动

C++ 在新函数声明符语法中访问它

c++ - unique_ptr 应该用于类成员指针吗?

c++ - 派生类型名

c++ - 使用 ATOMIC_FLAG_INIT 和 std::atomic_flag::clear 有什么区别