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

Consider the following using template template options ...

#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 it possible to delete the template parameter T? For example, is there a way to do the next job?

//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;
}
+3
source share
4 answers

I assume that you are after X, as well as A, in your code.

The usual pattern is

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

and then inside classes suitable for replacement:

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

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

+8
source

. , : A<int> ! -, :

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

B< A<int> > b;

.

A<int>, , , :

template<typename T>
struct A {
    template<typename U>
    struct rebind {
        typedef A<U> type;
    };
};

template<typename C>
struct B {
    typename C::template rebind<float>::type c;
};

B< A<int> > b;

B< A<int> >::c A<float>. typename C:: , ::type - , -. template C:: , rebind<float> , .

+4

:

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

int main()
{
    B< A<int> > b;
    return 0;
}
+1
source

You can nest parameters. That is, the parameter value can be parameterized.

template <typename X>
struct A
{
  X t;
};

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

int main()
{
  B< A<int> > b;
  return 0;
}

In this example, declaration bin main()creates a specialization Ausing intas a parameter, then creates a specialization busing A<int>as a parameter. Thus, by specialization b, Cthere is A<int>.

+1
source

All Articles