假设我有一个模板类是这样的:测试,如果模板参数定义一个特定的类型名称
template<typename T>
class Foo {};
像一个类:
class PossibleArg
{ typedef int required_type; }
是否可以写在类Foo一个static_assert它检查T :: required_type是否被定义?
假设我有一个模板类是这样的:测试,如果模板参数定义一个特定的类型名称
template<typename T>
class Foo {};
像一个类:
class PossibleArg
{ typedef int required_type; }
是否可以写在类Foo一个static_assert它检查T :: required_type是否被定义?
或许真的是这样的:
template <typename T>
class Foo {
static_assert(sizeof(T::required_type) > 0, "Never shows up");
};
编辑:其他方式:SFINAE
template <typename T>
struct has_required_type
{
typedef char yes[1];
typedef char no[2];
template <typename C>
static yes& test(typename C::required_type*);
template <typename>
static no& test(...);
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
template <typename T>
class Foo {
static_assert(has_required_type<T>::value, "Hasn't required type");
};
您可以使用BOOST_MPL_HAS_XXX_TRAIT_DEF,在Boost.MPL:
BOOST_MPL_HAS_XXX_TRAIT_DEF(required_type)
BOOST_MPL_ASSERT((has_required_type<PossibleArg>));
BOOST_MPL_HAS_XXX_TRAIT_DEF是一个宏观的,采取的名字xxx
作为参数,如果T定义一个名为xxx
嵌套类型生成元函数has_xxx<T>
计算结果为真。
(注意,MPL元函数是一个编译时功能,其结果可以用::type
进行访问。在这种情况下,结果是一个编译时的布尔常量(即bool_。)
如果你的目标是?得到一个编译错误,如果T没有一个required_type你可以只的typedef它美孚还是我失去了一些东西
template<typename T>
class Foo {
typedef typename T::required_type T_required_type;
};
是的,那是我现在如何解决问题。但是因为C++ 0x定义了static_assert,所以使用它似乎是一个更好的解决方案。 – cytrinox 2011-03-14 21:20:05
如果你实际上是在寻找static_assert,有类似的东西在这里 - Static assert without boost or C++0x
我寻找不需要三阶解决方案党的库像增强。 – cytrinox 2011-03-14 21:18:37