Partial template binding, create new template as type

假装没事ソ 提交于 2019-12-08 02:47:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18057750/partial-template-binding-create-new-template-as-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!