假設我有以下代碼:
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
};
我嘗試初始化一個類變數取決于具有相同名稱但型別和值不同的模板型別。我怎樣才能做到這一點?我可能正在尋找適用于 c 11 的解決方案。
uj5u.com熱心網友回復:
這是一個簡單的方法:
#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;
}
};
uj5u.com熱心網友回復:
您可以使用標簽調度(使用委托建構式):
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];
};
uj5u.com熱心網友回復:
您可以將不同的部分移動到單獨的班級并進行專業化。(或者如果合適,你可以進行全班專業化)
template <Type T>
struct MyData;
template <>
struct MyData<Type::Type32>{
uint32_t arr[4] = { 0x1234, 0x5678, 0x9ABC, 0xDEF0 };
};
template <>
struct MyData<Type::Type64>{
uint64_t arr[2] = { 0x12345678, 0x9ABCDE };
};
template<Type T>
class MyClass: private MyData<T>{
// common functions
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513358.html
標籤:C c 11模板
