Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is a simple way:

#include <array>
#include <cstdint>
#include <type_traits>

enum class Type { Type32, Type64 };

template <Type>
struct As128Bits;

template <>
struct As128Bits<Type::Type32> {
    using Integer = std::uint32_t;

    std::array<Integer, 4> data{0x1234, 0x5678, 0x9ABC, 0xDEF0};
};

template <>
struct As128Bits<Type::Type64> {
    using Integer = std::uint64_t;

    std::array<Integer, 2> data{0x12345678, 0x9ABCDE};
};

template <Type T>
struct MyClass : private As128Bits<T> {
    using Integer = typename As128Bits<T>::Integer;
    using As128Bits<T>::data;

    Integer getSum() {
        Integer sum = 0;
        for (auto const val : data) {
            sum += val;
        }
        return sum;
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading