我将在我看到的两个部分中组合问题:首先,按类型(A1,A2 与 B1,B2)进行区分,其次,通过变量的初始化进行区分。既然你说,代码都是一样的,但类型不是模板。所以我的第一次尝试是:
template <class X1, class X2>
struct MyStrategy {
  void foo()
  {
    X1 a = /* create appropiate X1 */;
    X2 b = /* create appropiate X2 */;
    // code that is the same for both except for the types...
  }
};
当然,该函数将具有参数和/或返回类型,但您明白了要点。
现在到第二部分,我在评论中留下的部分:值的初始化。我会通过某种基于策略的设计来实现这一点。第一张草图:
template <class X1, class X2>
struct X1X2Creator;
template <> 
struct X1X2Creator<A1, A2> {
  A1 createX1() { return function1_A(); }
  A2 createX2() { return function2_A(); }
};
template <> 
struct X1X2Creator<B1, B2> {
  B1 createX1() { return function1_B(); }
  B2 createX2() { return function2_B(); }
};
template <class X1, class X2>
struct MyStrategy : X1X2Creator<X1, X2> {
  void foo()
  {
    X1 a = this->createX1();
    X2 b = this->createX2();
    // code that is the same for both except for the types...
  }
};
this->createX1()请注意,由于它们的依赖名称,您必须通过 调用创建函数,否则编译器应该会抱怨。您也可以明确限定函数 ( X1X2Creator<X1, X2>::createX1())。
您可以根据需要改进该设计,例如不使用继承,而是实例化 X1X2Creator 并调用函数或将它们设为静态。如果您想使用更多不同类型的组合,请为每种类型使用一个创建策略:
template <class X1, class X2>
struct MyStrategy {
  void foo()
  {
    X1 a = CreationPolicy<X1>::create();
    X2 b = CreationPolicy<X2>::create();
    // code that is the same for both except for the types...
  }
};
如果您希望能够对相同类型使用不同的策略,请提供策略类作为模板参数:
template <class X1, class X2, 
  class X1Creator = CreationPolicy<X1>,
  class X2Creator = CreationPolicy<X2>>
struct MyStrategy {
  void foo()
  {
    X1 a = X1Creator::create();
    X2 b = X2Creator::create();
    // code that is the same for both except for the types...
  }
};
高温高压