gpt4 book ai didi

c++ - 将 C++ 模板的使用限制为 POD 类型

转载 作者:IT老高 更新时间:2023-10-28 12:59:05 26 4
gpt4 key购买 nike

我有一个 c++ 模板类,它只有在模板化类型是普通旧数据时才能正确运行。任何带有构造函数的东西都不能正常工作。

当有人尝试这样做时,我想以某种方式获得编译时或运行时警告。

//this should generate error
myclass<std::string> a;

//this should be fine
myclass<int> b;

有什么诀窍吗?

最佳答案

#include <type_traits>

template<typename T>
class myclass
{
static_assert(std::is_pod<T>::value, "T must be POD");

// stuff here...
};

如果你传递一个非POD类型作为模板参数,上面会导致编译错误。此解决方案需要 C++11 用于 <type_traits>标题和 static_assert关键字。

编辑:如果您的编译器支持 TR1(大多数都支持),您也可以在 C++03 中实现它:

#include <tr1/type_traits>

template<typename T>
class myclass
{
static char T_must_be_pod[std::tr1::is_pod<T>::value ? 1 : -1];

// stuff here...
};

关于c++ - 将 C++ 模板的使用限制为 POD 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19154080/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com