简体   繁体   中英

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>') .

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.

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:

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]); may not do what you think it does - it is exactly equivalent to Vector(const T *data); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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