0
votes
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?

1
You're trying to cast it to float, not to Colordata<float>. - Thomas
@Thomas I also tried to use Colordata<TCast> convert() (without operator). Same error. - Wusiki Jeronii
Also your CTOR requires the length to be a compile time constant. So your cast won't work as the CTOR of Colordata<float> can't be called with length as N: gcc.godbolt.org/z/vGWsrdGMd - Simon Kraemer
@SimonKraemer it works without length (dynamic array). But how can I set up the constructor to get length using static array? - Wusiki Jeronii

1 Answers

2
votes

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.