Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare/define a class with template template parameters without using an extra template parameter

Consider the following use of template template parameters...

#include <iostream>

template <typename X>
class A
{
    X _t;
public:
    A(X t)
        :_t(t)
    {
    }
    X GetValue()
    {
        return _t;
    }
};

template <typename T, template <typename T> class C >
class B
{
    C<T> _c;
public:
    B(T t)
        :_c(t)
    {
    }
    T GetValue()
    {
        return _c.GetValue();
    }
};

using namespace std;

int main()
{
    B<int, A> b(10);
    cout<<b.GetValue();
    return 0;
}

Is there a way by which the template parameter T can be removed? For example is there a way to make the following work?

//Does not compile
template <template <typename T> class C >
class B
{
    C _c;
public:
    B(T t)
        :_c(t)
    {
    }
    T GetValue()
    {
        return _c.GetValue();
    }
};

int main()
{
    B< A<int> > b(10);
    cout<<b.GetValue();
    return 0;
}
like image 704
Autodidact Avatar asked Jan 21 '26 01:01

Autodidact


1 Answers

I assume you're after X, as well as A, in your code.

The usual pattern is to have

template<typename C>
struct B
{
   C c;
};

and then, inside classes eligible for substitution:

template<typename X>
class A
{
   typedef X type_name;
   X t;
};

Then you can access the template parameter using C::type_name.

like image 161
Sunlight Avatar answered Jan 22 '26 14:01

Sunlight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!