部分模板绑定,创建新模板作为类型 [英] Partial template binding, create new template as type
问题描述
是否存在将模板部分绑定到参数类型的方法?例如,我有以下模板:
template<typename T, typename Q> struct generic { };
我还有另一个模板,它以模板类为参数,希望能够用第一种类型创建它的实例:
template<typename T, template<typename> class Impl>
struct wrapper {
Impl<T> foo;
};
这将接受一个简单的模板,如template<typename T>
而不进行任何更改.我现在想做的是部分绑定generic
模板,仅指定Q
并将其传递给wrapper
.组成一些语法,也许像这样:
template<typename T> bound = generic<T,some_type>;
我知道我几乎可以通过继承得到我想要的东西:
template<typename T> bound : public generic<T,some_type> { };
我希望能避免这种情况,因为它会导致基类中定义的构造函数和运算符出现问题.
在C ++ 11中,您可以使用模板别名
template<class X>
using Bind_CPP11 = generic<X, Y>;
template<class X, template<class> class Impl>
struct wrapper_CPP11
{
Impl<X> foo;
};
在C ++ 98/03中,您可以使用简单的 类组成 (I不会在这里使用继承)
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
};
实时示例 ./p>
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.
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
};
这篇关于部分模板绑定,创建新模板作为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!