c – 如何检查模板类型是否是变体类型的类型之一?

考虑变体类型和模板函数,如何检查模板类型是变体的类型之一?有比以下更优雅的方式吗?
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版本兼容.

解决方法

使用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);
}

DEMO

或者手动迭代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<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<void,BOOST_VARIANT_ENUM_SHIFTED_ParaMS(Ts)> > : boost::false_type {};

DEMO 2

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...