Home > Back-end >  Cast custom struct to another template type
Cast custom struct to another template type

Time:09-17

template <typename T>
struct Colordata
{
public:
    T *data;
    unsigned long size;
    unsigned long length;

    template <size_t N>
    Colordata(T (&arr)[N])
    {
        length = N;
        size = sizeof(arr);
        T dataArr[length];
        for (int i = 0; i < N; i  )
        {
            dataArr[i] = arr[i];
        }
        data = dataArr;
    }
    template <typename TCast>
    operator TCast() const
    {
        TCast dataCastTmp[length];
        for (int i = 0; i < length; i  )
        {
            dataCastTmp[i] = (TCast)data[i];
        }
        return Colordata<TCast>(dataCastTmp);
    }
};

int main(int argc, char const *argv[])
{
    int arr[] = {12, 434, 54};
    auto a = Colordata<int>(arr);
    auto b = (float)a;
    return 0;
}

When I tried to convert Struct<typename> to Struct<another typename> another typename doesn't exist. I think so 'cos I get error in the compiler log:

no matching function for call to «Colordata::Colordata(float [((const Colordata*)this)->Colordata::length])»

Is there any way to casting template struct to template struct?

CodePudding user response:

There are many problems with this code, but the one you asked about is happening because of the signature of the conversion operator:

    template <typename TCast>
    operator TCast() const

If you try to cast to a Colordata<float> then TCast will be the type Colordata<float>, and not float as the implementation assumes.

The solution is to only allow conversions to other Colordata instantiations:

    template <typename TCast>
    operator Colordata<TCast>() const

Now TCast will be float as desired, and you're one step closer to correct code.


The other problems are the use of variable-length arrays (not supported in C ), and storing pointers to local variables that outlive their scope leading to undefined behaviour. Use std::vector to make life easier and safer.

  • Related