1

This is my code. How do I make A::type be int or double or whatever else is used to make instances of class B?

template<class X>
class A
{
typedef "*****" type
........
.....
......
}
template<class Y>
class B
{
......
.......
....
}
int main()
{
B<int> x;
A<B<int> > y;
.....
....
....
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Tilak Raj Singh
  • 353
  • 2
  • 5
  • 15

3 Answers3

3

This would do it.

template<class X>
class A
{
    typedef typename X::type type;
};

template<class Y>
class B
{
public:
    typedef Y type;
};
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • Of course, this will only work if `B` is actually used as the parameter when declaring instances of `A`. – Remy Lebeau Apr 26 '13 at 00:08
  • @RemyLebeau well it will work if there's a type(def) named `type` in the template argument. Would partial specialization be any better? – dyp Apr 26 '13 at 00:09
  • 2
    @DyP Yes it would be better, if implemented like in [0x499602D2](http://stackoverflow.com/users/701092/0x499602d2)'s answer. – dyp Apr 26 '13 at 00:19
2

Perhaps like this:

template <typename T>
struct B
{
    typedef T type;
    // ...
};

template <typename> struct A { /* ... */ };


typedef B<int> MyB;

int main()
{
    MyB          x;
    A<MyB::type> y;
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

Maybe this will help.

template <class T>
class B;

template <class T>
class A {
    public:
        typedef T type;
};

template <class T>
class A<B<T>> : public A<T> {};

template <class T> class B {};

int main()
{
    A<B<int>>::type x;
}
David G
  • 94,763
  • 41
  • 167
  • 253