fol*_*bis 1 c++ templates c++11
假设我有以下代码:
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
};
Run Code Online (Sandbox Code Playgroud)
我尝试根据具有相同名称但不同类型和值的模板类型来初始化类变量。我怎样才能做到这一点?我可能正在寻找一个适用于 c++11 的解决方案。
这是一个简单的方法:
#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;
}
};
Run Code Online (Sandbox Code Playgroud)
您可以使用标签调度(带有委托构造函数):
template<Type T>
class MyClass
{
public:
using MyType = typename std::conditional<T == Type::Type32, uint32_t, uint64_t>::type;
// This will call one of the constructors below
MyClass() : MyClass(std::integral_constant<Type, T>{}) {}
MyType getSum() { /* ... */ }
private:
explicit MyClass(std::integral_constant<Type, Type::Type32>) : arr{ 0x1234, 0x5678, 0x9ABC, 0xDEF0 } {}
explicit MyClass(std::integral_constant<Type, Type::Type64>) : arr{ 0x12345678, 0x9ABCDEF0 } {}
MyType arr[T == Type::Type32 ? 4 : 2];
};
Run Code Online (Sandbox Code Playgroud)