By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 912 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

conditional typedef in templates

P: n/a
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

Mar 12 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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;
}
Mar 12 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.