1

I have a class where I want the template parameter B to have a default type. The problem is that the default type is a complicated expression depending also on the type of A.

The following code illustrates the situation but does obviously not compile, because defaultB type is not know inside the template expression.

template<class A, class B = defaultB>
class Foo{

   typedef A::Bar Bar;
   typedef Bar::Ex defaultB;


};

Does anybody have an idea how to solve this problem properly?

user695652
  • 4,105
  • 7
  • 40
  • 58
  • Isn't that simpler -> `template `? – myaut Apr 16 '15 at 10:04
  • @myaut Thank you! Well the above example is an extreme simplified version of the situation, the problem is that A::Bar::Ex is in fact a very complicated expression. – user695652 Apr 16 '15 at 10:06

2 Answers2

3

You could maintain a namespace of defaults like this:

namespace detail {
    template <typename A>
    using defaultB = typename A::Bar::Ex;
}

template<class A, class B = typename detail::defaultB<A>>
class Foo{
};

This lets you have as complex expressions as you like in your detail namespace without making the Foo declaration ugly.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

An alternative to TartanLlama's excellent suggestion is to maintain a dummy type hierarchy to lift up the typedef's into scope:

template<class A> 
struct _Foo {
    typedef typename A::Bar Bar;
    typedef typename Bar::Ex defaultB;
};

template<class A,class B=typename _Foo<A>::defaultB>
struct Foo : _Foo<A> {
};
Andy Brown
  • 11,766
  • 2
  • 42
  • 61