jeudi 29 septembre 2022

Conditionally initialize class variable depending on the template type

Suppose I have the following code:

enum class Type
{
    Type32,
    Type64
};

template<Type T>
class MyClass
{
public:
    using MyType = typename std::conditional<T == Type::Type32, uint32_t, uint64_t>::type;
    
    MyType getSum()
    {
        MyType sum = 0;
        for(size_t i = 0;i < sizeof(arr);i ++)
        {
            sum += arr[i];
        }
        return sum;
    }

 private:
     //MyType arr[4] = { 0x1234, 0x5678, 0x9ABC, 0xDEF0 }; // for Type::Type32
     //MyType arr[2] = { 0x12345678, 0x9ABCDE }; // for Type::Type64
};

I try to initialize a class variable depends on the template type with the same name but different type and value. How can I do that? I probably looking for a solution that works in c++11.

Aucun commentaire:

Enregistrer un commentaire