如何检查模板类型是否是变体类型的类型之一?
How to check if a template type is one of the types of a variant type?
考虑变体类型和模板函数,如何检查模板类型是变体类型之一?有没有比下面的方法更优雅的方法?
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);
}
或手动遍历 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 {};
考虑变体类型和模板函数,如何检查模板类型是变体类型之一?有没有比下面的方法更优雅的方法?
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);
}
或手动遍历 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 {};