【问题标题】:Nested Template Specialization嵌套模板专业化
【发布时间】:2012-06-25 19:45:18
【问题描述】:

当模板参数与类的类型相同时,我有一个需要专门构造函数的模板类。下面的代码不会编译。

当类型为 Dual 时,指定使用特定构造函数的正确语法是什么?特别是,当模板参数的类型为 Dual 时,我需要在初始化器列表中初始化成员 'real',但如果不是(例如 double 类型)则不需要。

template<class X> class Dual {
 public:
  X real;
  size_t N;
  std::vector<X> imag;//don't know N at compile time


  Dual(size_t _N);

};

template <class X>
inline Dual<X>::Dual(size_t _N):  N(_N), imag(N, 0.0)  {}

template <class X>
inline Dual<Dual<X> >::Dual(size_t _N): real(_N), N(_N), imag(_N, 0.0) {}
//syntax error:  
//error: cpptest.cpp:20:24: error: C++ requires a type specifier for all declarations
//inline Dual<Dual<X> >::Dual(size_t _N): real(_N), N(_N), imag(_N, 0.0) {}
//~~~~~~ 



int main(){

  Dual <double> a(5);
  Dual< Dual < double>> b(5);

}

【问题讨论】:

  • 相关但非直接原因:您没有默认构造函数。您如何处理没有默认构造函数的类型的默认构造,就像在嵌套声明中所做的那样?
  • 这就是我试图通过专业化解决的问题。 X 类型要么是 Dual,它需要调用 1 参数构造函数,要么是某种浮点类型,在这种情况下它不需要(值稍后分配)。
  • 那么应该很明显:将默认构造函数添加到您的Dual 类。
  • 带有模板参数 Dual 的默认构造函数将使对象保持一半初始化(参数给出了包含向量的大小)。

标签: c++ templates template-specialization explicit-specialization


【解决方案1】:

你可以为你的构造函数提供一个可选的第二个参数来初始化real

template<class X> class Dual {
public:
  X real;
  size_t N;
  std::vector<X> imag;
  Dual(size_t _N, X x = X());
};

template <class X>
inline Dual<X>::Dual(size_t _N, X x):  real(x), N(_N), imag(N, 0.0)  {}

现在,当您拥有特殊的Dual 时,您可以通过传入“原型”以您想要的方式对其进行初始化。

Dual<double> a(5);
Dual< Dual<double> > b(5, a);

优点是您只需声明一个template。但是,如果您为 Dual&lt; Dual&lt;X&gt; &gt; 创建一个特化,那么您可以像您尝试过的那样定义构造函数(除了 imag 初始化错误,并在下面更正)。

// Specialize Dual<T> in the case T is a Dual<X>
template <class X> class Dual< Dual<X> > {
public:
    Dual<X> real;
    size_t N;
    std::vector< Dual<X> > imag;
    Dual(size_t _N);
};

template <class X>
inline Dual< Dual<X> >::Dual(size_t _N)
    : real(_N), N(_N), imag(N, Dual<X>(_N)) {}

【讨论】:

    【解决方案2】:

    您不能提供非类型模板的部分特化,其中包括您的构造函数。

    【讨论】:

    • 能否详细说明为什么构造函数是非类型模板?
    • @BenJones:构造函数不是类型。您只能部分专门化类型。另一方面,您可以完全特化模板的函数成员,但它必须是完全特化。在您的情况下,您正在尝试部分专门化 Dual&lt;X&gt; 的构造函数(对于任何 X)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多