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?

1
  • I'm search for a solution which doesn't require third-party libs like boost. Commented Mar 14, 2011 at 21:18

4 Answers 4

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"); }; 
Sign up to request clarification or add additional context in comments.

Comments

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_.)

Comments

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; }; 

1 Comment

Yes, thats how I solve the problem for now. But since C++0x defines static_assert, using it seems a nicer soltion.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.