我有一个模板类 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 http://www.boost.org/doc/libs/1_58_0/doc/html/boost_staticassert.html
- 使用 TypeTraits 库进行检查:http://www.boost.org/doc/libs/1_58_0/libs/type_traits/doc/html/boost_typetraits/reference/is_same.html
例如
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/