是否有某种方法可以将模板部分绑定(bind)到参数类型?例如,我有以下模板:
template<typename T, typename Q> struct generic { };
我有另一个模板,它接受模板类作为参数,期望能够使用第一种类型创建它的实例:
template<typename T, template<typename> class Impl>
struct wrapper {
Impl<T> foo;
};
这将接受一个简单的模板,例如 template<typename T>
无需更改。我现在想做的是部分绑定(bind)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 中,您可以使用简单的 class composition (我不会在这里使用继承)
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
};
关于c++ - 部分模板绑定(bind),创建新模板作为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18057750/