2

Is there some way to partially bind a template to parameter types? For example, I have the following template:

template<typename T, typename Q> struct generic { };

And I have another template which takes a template class as a parameter, expecting to be able to create instances of it with the first type:

template<typename T, template<typename> class Impl>
struct wrapper {
    Impl<T> foo;
};

This would accept a simple template like template<typename T> without changes. What I want to do now is partially bind the generic template, specifying only Q and passing it to wrapper. Making up some syntax, perhaps something like this:

template<typename T> bound = generic<T,some_type>;

I know I can almost get what I want using inheritance:

template<typename T> bound : public generic<T,some_type> { };

I am hoping though to avoid this though as it causes issues with constructors and operators defined in the base class.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
edA-qa mort-ora-y
  • 30,295
  • 39
  • 137
  • 267

1 Answers1

4

In C++11 you can use template aliases

template<class X>
using Bind_CPP11 = generic<X, Y>;

template<class X, template<class> class Impl>
struct wrapper_CPP11
{
    Impl<X> foo;
};

In C++98/03, you can use simple class composition (I would not use inheritance here)

template<class X>
struct Bind_CPP03
{
    typedef generic<X, Y> type;
};

template<class X, template<class> class Impl>
struct wrapper_CPP03
{
    typename Impl<X>::type foo;
//  ^^^^^^^^ to extract dependent type
};

Live Example.

Community
  • 1
  • 1
TemplateRex
  • 69,038
  • 19
  • 164
  • 304