检查模板类型是否在可用类型列表中
Check a template type is in a list of available types
我有一个模板 class Foo
。我写了它的模板以避免代码的大量重复,但是这个 class 必须只与一些特定的其他 classes 一起使用。
如果没有 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);
如果支持的类型列表较长,请为它们提供单碱基 class 并使用特征 is_base_of 或检查 boost MPL 库
我有一个模板 class Foo
。我写了它的模板以避免代码的大量重复,但是这个 class 必须只与一些特定的其他 classes 一起使用。
如果没有 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);
如果支持的类型列表较长,请为它们提供单碱基 class 并使用特征 is_base_of 或检查 boost MPL 库