2

Assume I have a template class like this:

template<typename T>
class Foo {};

And a class like:

class PossibleArg
{ typedef int required_type; }

Is it possible to write a static_assert in class Foo which checks if T::required_type is defined?

cytrinox
  • 1,846
  • 5
  • 25
  • 46

4 Answers4

3

Maybe something looks like:

template <typename T>
class Foo {
  static_assert(sizeof(T::required_type) > 0, "Never shows up");
};

EDIT: Other way: 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");
};
Oleg Svechkarenko
  • 2,508
  • 25
  • 30
2

You can use BOOST_MPL_HAS_XXX_TRAIT_DEF, in Boost.MPL:

BOOST_MPL_HAS_XXX_TRAIT_DEF( required_type )

BOOST_MPL_ASSERT(( has_required_type< PossibleArg > ));

BOOST_MPL_HAS_XXX_TRAIT_DEF is a macro, taking a name xxx as parameter, which generates a metafunction has_xxx< T > that evaluates to true if T define a nested type named xxx.

(Note that an MPL metafunction is a compile-time function whose result can be accessed using ::type. The result in this case is a compile-time boolean constant(i.e. a bool_.)

Luc Touraille
  • 79,925
  • 15
  • 92
  • 137
2

If your goal is to get a compiler error if T doesn't have a required_type you could just typedef it in Foo. Or am I missing something?

template<typename T>
class Foo {
  typedef typename T::required_type T_required_type;
};
Erik
  • 88,732
  • 13
  • 198
  • 189
  • Yes, thats how I solve the problem for now. But since C++0x defines static_assert, using it seems a nicer soltion. – cytrinox Mar 14 '11 at 21:20
0

If you're actually looking for static_assert, there's something similar over here - Static assert without boost or C++0x

Community
  • 1
  • 1
celavek
  • 5,575
  • 6
  • 41
  • 69