如何减少模板参数的数量?

3


我需要将一个有两个参数的模板改为只有一个参数的模板。

我想要绑定模板的第一个参数:

template<class T1, class T2>
struct Two_Parameter_Template {
   // Two ctor's
   Two_Parameter_Template() { };
   template<class Param>
   Two_Parameter_Template(Param) { /* ... */ }
};

通过使用另一种(非侵入式)模板机制:
//bind the first parameter of a template "bound", this template should work as 
//an adapter reducing the number of parameters required
template<class X, template<class, class> class bound>
struct bind_1st {
   template<class T> // this is the resulting one parameter template
   struct eval {
       eval () {
           bound<X, T>();
       }
       template<class T2>
       eval (T2 obj) {            
           bound<X, T>(obj);            
       }
   };
};  

为了以后可以将此模板用作另一个模板的参数,该模板少了一个自己的参数(类似下面的内容):

template <template<class> class One_Parameter_Template>
struct SomeTemplate {
   //...
};

// Later in the code
typedef SomeTemplate<bind_1st<Bound_Param_class, Two_Parameter_Template> >::eval    ConcreteClass;

问题是 - C++中是否有语法来支持这一点。
最好的问候, Marcin

你能让你的例子更具体一些吗? - GManNickG
在这个例子中,Two_Parameter_Template是一个检查策略,可以抛出类型为T1的异常。我需要预先定义异常的类型(这样该策略的“可见”参数数量将为1而不是2),并将该策略传递给另一个模板。 - Marcin
1个回答

1

你可以使用boost mpl bind来实现这个功能

但是它可能不会完全按照你的期望行为执行

编辑: 我看到你在代码中犯了一个小错误,导致它不能按照你的期望工作:

typedef SomeTemplate< bind_1st<Bound_Param_class, Two_Parameter_Template>::eval > ConcreteClass;

如果你把eval放进去,它就能正常工作了。这可能是解决你问题最简单的方法。希望这次我能更好地理解你的问题;-)


感谢您提供精确的答案。困难的部分在于我需要绑定“Two_Parameter_Template”模板的第一个参数,而将其余参数保留为未指定状态。在绑定后,该模板不能被“完全”具体化。第二个参数必须稍后传递。 - Marcin
我刚刚意识到你的代码几乎可以正常工作了。请参见上面的编辑。 - Vinzenz
就这样!我简直不敢相信我因为一个如此愚蠢的打字错误而发布了这个问题 :). 模板的语法可能会让人发疯... 非常感谢你发现了这个错误。 - Marcin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接