n.************@gmail.com wrote:
What I'd like to do:
template<typename T>
struct s {
typedef typename T::foo foo; // define if and only if T::foo
exists
};
Can I do something like this with templates (AFAIK not), and if not,
are there other patterns you think I should be looking at?
TIA
This might not the be the best way to approach this but
this uses partial template specialization and boost::mpl
to help. Might choke some compilers.
----------------------------------------------------------
#include <vector>
#include <boost/mpl/has_xxx.hpp>
BOOST_MPL_HAS_XXX_TRAIT_DEF( iterator )
using namespace std;
template<typename T, bool enable = has_iterator<T>::value >
struct s;
template<typename T>
struct s<T, true>
{
// has foo (calling it iterator)
typedef typename T::iterator iterator;
T* m_internal;
};
template<typename T>
struct s<T, false>
{
// no foo
T* m_internal;
};
int
main()
{
typedef s< vector<int has_iter;
typedef s< int no_iter;
has_iter foo;
has_iter::iterator fooIter;
no_iter bar;
// uncomment this line to generate no a no-iterator error
//no_iter::iterator barIter;
}