c++ - 检查模板类型是否在可用类型列表中

标签 c++ templates c++98

我有一个模板类 Foo。我写了它的模板以避免代码的大量重复,但是这个类必须只与一些特定的其他类一起使用。

如果没有 C++11,我该如何检查?

目前,我要写的解决方案是这样的:

template <typename T> inline
bool is_type_available() { return false; }
template <> inline
bool is_type_available<Bar>() { return true; }
template <> inline
bool is_type_available<Baz>() { return true; }

template <typename T>
class Foo
{
  public:
    Foo() { assert(is_type_available<T>()); }
};

我觉得它不是那么丑,但我希望能有更好的东西存在。

最佳答案

使用 Boost 库(仅 header ):

例如 BOOST_STATIC_ASSERT(boost::is_same<T, Bar>::value || boost::is_same<T, Baz>::value);

如果支持的类型列表较长,要么为它们提供单个基类并使用 trait is_base_of 要么检查 boost MPL 库

关于c++ - 检查模板类型是否在可用类型列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30803652/

相关文章:

c++ - VC++ 模板编译器错误 C2244 : Unable to Match Function Definition to an Existing Declaration

c++ - 如何用宏做static_assert?

c++ - 从 xlslib 构建 dll 文件

php - view=category 上的 joomla 模板

c++ - Visual Studio 2010 上 C++ 中外部数组允许的最大数组大小

html - 在自己的网站上实现 Bootstrap 导航栏

c++ - 如何在构造函数中限制字符数组长度

c++ - 使用 C++98 标准编写的代码可以用新的编译器编译吗?

c++ - 在 macOS 中使用 C/C++ 设置鼠标光标图像

c++ - Eclipse CDT 编辑器无法识别 OpenGL 扩展