conditional typedef in templates

N

n.torrey.pines

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
 
P

Piyo

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top