简体   繁体   English

模板专业化没有匹配的构造函数

[英]Template specialization no matching constructor

I am creating a templated vector class that is roughly done in the following way: 我正在创建一个模板化的矢量类,大致通过以下方式完成:

// Main class
template <typename T, int DIMS>
class Vector
{
    // Default constructor
    Vector();
    // Data constructor
    Vector(const T data[DIMS]);

    // Other functions, variables, operators
};

// 3d specialization
template <typename T>
class Vector<T, 3>
{
    // Cross product for 3d vectors -- only thing in specialization
    static Vector<T, 3> cross(const Vector<T, 3> a, const Vector<T, 3> b);
};

For the main template, I have a default constructor as well as a constructor specifying the elements. 对于主模板,我有一个默认构造函数以及一个指定元素的构造函数。 When I try to compile using the constructor with the elements, I get the error no matching constructor for initialization of 'Vec3f' (aka 'Vector<float, 3>') . 当我尝试使用带有元素的构造函数进行编译时,出现错误, no matching constructor for initialization of 'Vec3f' (aka 'Vector<float, 3>')

Everything similar question that I have looked at indicates that the constructors should automatically work with templated classes, so I'm not sure what is going on here. 我看过的所有类似问题都表明,构造函数应自动使用模板化类,因此我不确定这里发生了什么。 I previously had constructor errors with classes that didn't have a template specialization and it listed that the other constructor was not viable, which makes me think that the constructor isn't being copied to the templated class for some reason. 我以前在没有模板专门化的类上遇到构造函数错误,并且列出了另一个构造函数不可行,这使我认为该构造函数由于某种原因没有被复制到模板化类中。

Partial and explicit specializations do not inherit anything from the primary template; 部分和显式专业化不会从主模板继承任何内容; they are completely unrelated. 它们是完全无关的。 In your code, a Vector<T, 3> is a completely empty class except for the static member function. 在您的代码中,除了静态成员函数之外, Vector<T, 3>是一个完全空的类。

There are ways to reduce code duplication when a partial/explicit specialization share code with the primary template (for instance, by inheriting from a base class template that implements the shared functionality), but in this case I see no reason to write a partial specialization in the first place. 当部分/显式专业化代码与主模板共享代码时,有多种方法可以减少代码重复(例如,通过从实现共享功能的基类模板继承),但是在这种情况下,我认为没有理由编写部分专业化代码首先。 Just make cross a free function template: 只需将cross作为免费功能模板即可:

template <typename T, int DIMS>
class Vector
{
    // Default constructor
    Vector();
    // Data constructor
    Vector(const T data[DIMS]);

    // Other functions, variables, operators
};

template<typename T>
Vector<T, 3> cross(const Vector<T, 3> a, const Vector<T, 3> b);

As a side note, Vector(const T data[DIMS]); 作为附带说明, Vector(const T data[DIMS]); may not do what you think it does - it is exactly equivalent to Vector(const T *data); 可能不执行您认为的操作-完全等同于Vector(const T *data); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM