如何检查模板类型是否为变量类型的类型之一? [英] How to check if a template type is one of the types of a variant type?
本文介绍了如何检查模板类型是否为变量类型的类型之一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑变体类型和模板功能,如何检查模板类型是否是变体类型之一?是否有比以下更优雅的方法?
Considering a variant type and a template function, how can I check the template type is one of the types of the variant ? Is there a more elegant way than the following ?
typedef boost::variant<Foo,Bar> Var;
template <typename T>
void f(const T& x)
{
BOOST_STATIC_ASSERT(
boost::is_same<T,Foo>::value
|| boost::is_same<T,Bar>::value
);
}
注意:我使用Boost 1.57和gcc 4.8 .3。 我不使用C ++ 11 与旧的gcc版本兼容。
Note : I use Boost 1.57 and gcc 4.8.3. I don't use C++11 for compatibility with old gcc versions.
推荐答案
使用MPL :
#include <boost/variant/variant.hpp>
#include <boost/mpl/contains.hpp>
typedef boost::variant<Foo, Bar> Var;
template <typename T>
void f(const T& x)
{
BOOST_STATIC_ASSERT(boost::mpl::contains<Var::types, T>::value);
}
或手动迭代 boost ::: variant
类型:
#include <boost/variant/variant_fwd.hpp>
#include <boost/type_traits.hpp>
template <typename T, typename V>
struct variant_has_type;
template <typename T, BOOST_VARIANT_ENUM_SHIFTED_PARAMS(typename Ts)>
struct variant_has_type<T, boost::variant<T, BOOST_VARIANT_ENUM_SHIFTED_PARAMS(Ts)> >
: boost::true_type {};
template <typename T, typename U, BOOST_VARIANT_ENUM_SHIFTED_PARAMS(typename Ts)>
struct variant_has_type<T, boost::variant<U, BOOST_VARIANT_ENUM_SHIFTED_PARAMS(Ts)> >
: variant_has_type<T, boost::variant<BOOST_VARIANT_ENUM_SHIFTED_PARAMS(Ts), void> > {};
template <typename T, BOOST_VARIANT_ENUM_SHIFTED_PARAMS(typename Ts)>
struct variant_has_type<T, boost::variant<void, BOOST_VARIANT_ENUM_SHIFTED_PARAMS(Ts)> >
: boost::false_type {};
这篇关于如何检查模板类型是否为变量类型的类型之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文