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.
>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;
}
};