It is possible, and there are many ways to implement this. All of them must return to some has_type attribute class so that has_type<T>::value true if the typedef member exists, and false otherwise. Suppose we already have this feature class. Then here is one solution using C ++ 11 template aliases:
template <typename T, bool> class FooImpl { // implement general case }; template <typename T> class FooImpl<T, true> { // implement specific case }; template <typename T> using Foo = FooImpl<T, has_type<T>::value>; // C++11 only
Now, to do a typetrait:
template<typename T> struct has_type { private: typedef char yes; typedef struct { char array[2]; } no; template<typename C> static yes test(typename C::context_type*); template<typename C> static no test(...); public: static const bool value = sizeof(test<T>(0)) == sizeof(yes); };
If you don't have C ++ 11, or if you don't want to rewrite the whole class, you can make the difference finer, for example. using std::enable_if , std::conditional etc. Post a comment if you need some specific examples.
source share