Cad*_*hon 6 c++ boost type-traits boost-variant c++98
考虑变体类型和模板函数,如何检查模板类型是变体的类型之一?有比以下更优雅的方式吗?
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
);
}
Run Code Online (Sandbox Code Playgroud)
注意:我使用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);
}
Run Code Online (Sandbox Code Playgroud)
或手动迭代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 {};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
698 次 |
| 最近记录: |