2
4

3 回答 3

3

另一种选择是像分配器一样执行它并在 and 中提供一个模板rebind,如果您可以访问这些模板:AB

template<class T>
struct A{
  template<class U>
  struct rebind{ typedef A<U> other; };
};

template<class AB>
struct C{
  typedef typename AB::template rebind<double>::other rebound_AB;
};
于 2012-05-26T02:16:36.503 回答
3

这可以通过引入我translate在以下代码中命名的帮助模板来解决:

template<class W>
struct A {
  typedef A type;
};

template<class W>
struct B {
  typedef B type;
};

template<class AB, class U>
struct translate {
};

template<template<typename> class AB, class W, class U>
struct translate<AB<W>, U> {
  typedef AB<U> type;
};

template<class AB>
struct C {
  // AB is A or B. If it's A we want to construct A<double>, if it's B                                                          
  // we want to construct B<double>:                                                                                            
  typedef typename translate<AB, double>::type D;
  D d;
};

int main(int argc, char** argv){
  C<A<int> > c1;
  C<B<int> > c2;
}
于 2012-05-26T02:12:36.080 回答
2

为此,您需要部分模板规范:

// base declaration is undefined
template< typename AorB > struct C;

// declaration for A<W>
template< typename W >
struct C< A< W > >
{
    typedef A< double > type;
};

// declaration for B<W>
template< typename W >
struct C< B< W > >
{
    typedef B< double > type;
};

适用于具有一个类型参数的任何模板类的更一般情况是:

// base declaration is undefined
template< typename AorB > struct C;

// declaration for T<W>
template< template< typename > class T, typename W >
struct C< T< W > >
{
    typedef T< double > type;
};
于 2012-05-26T02:11:16.970 回答