简体   繁体   中英

Conversion from strange template type

I have a number of vectors (the maths type) implemented as structs. There is a base Vector , which is a template, and then multiple implementations of the this template for vectors of different dimensions:

template<unsigned int D>
struct Vector
{
    float values[D];

    inline Vector<D> operator*(const Vector<D>& v) const
    {
        Vector<D> result;

        for (unsigned int i = 0; i < D; i++)
            result[i] = values[i] * v[i];

        return result;
    }

    float operator[](unsigned int i) const
    {
        return values[i];
    }
};

I have just included a single operator, but there are obviously others and various methods for taking the dot product etc. I then have implementations like so:

struct Vector2 : Vector<2>
{
    Vector2(float x = 0, float y = 0) : Vector<2>()
    { }
};

I then have two Vector2 s that I attempt to use the multiplication operator on like: Vector2 textureOffsetPixels = textureOffset * textureSampleSize;

And it throws the error: conversion from Vector<2u> to non-scalar type 'Vector2' requested . What is up with the Vector<2u> and why does this not work? Both variables are of explicit type Vector2 .

In order to be able to convert the result of textureOffset * textureSampleSize , which is a Vector<2> , into a Vector2 , you need a conversion function. A constructor like this will suffice:

Vector2(const Vector<2> &base) : Vector<2>(base) {}

The error mentions Vector<2u> because the template parameter is an unsigned int , so 2 is implicitly converted to 2u .

Your operator * returns Vector<2> , not Vector2 . The following will work:

Vector<2> a, b, c;
c = a * b;

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