gpt4 book ai didi

c++ - 用模板化函数替换仿函数

转载 作者:搜寻专家 更新时间:2023-10-31 00:52:48 31 4
gpt4 key购买 nike

我目前正在刷新我的一个旧 C++ 项目,试图利用现代 C++ 带来的所有好东西。该项目的某些部分是关于访问 uint8_t 数组,返回 uint8_t、uint16_t 或 uint32_t,具体取决于所需的数据。为了问题的简单性,我将把任何字节序相关的问题放在一边。

我做了以下类(class),使用仿函数访问数据:

template<std::size_t sz>
class Read
{
public:
template <std::size_t sz>
struct Read_traits { };

template <>
struct Read_traits<8> { using internal_type = std::uint8_t; };

template <>
struct Read_traits<16> { using internal_type = std::uint16_t; };

template <>
struct Read_traits<32> { using internal_type = std::uint32_t; };

template <>
struct Read_traits<64> { using internal_type = std::uint64_t; };

using read_type = typename Read_traits<sz>::internal_type;

template<typename T, ::std::size_t N>
read_type operator()(const ::std::array<T, N> & arr, const ::std::uint32_t& adr) const {
read_type returnValue{};
for (uint8_t i = 0; i <= sizeof(read_type) - 1; ++i) {
returnValue <<= 8;
returnValue |= arr[adr + i];
}
return returnValue;
};
};

用法是

int main()
{
std::array <uint8_t, 0x4> memory {0xFE, 0xDC, 0xBA, 0x98};
Read<32> r32;
auto val32 = r32(memory, 0);
std::cout << "32 bits: 0x" << std::hex << val32 << std::endl;

return 0;
}

It works the way I want, but I was wondering if it was possible to create a regular function in place of the functor, still using the traits ?

IE replacing the 2 lines functor call :

Read<32> r;
auto val = r(memory, 0);

by a single line function :

auto val Read<32>(memory, 0);

我尝试了一些没有定论的事情,而且由于我远不是模板方面的专家,我可能正在追求一些甚至不可行的事情......

感谢阅读我:)

最佳答案

你可以这样做:

// Maps 8, 16 and 32 to uint8_t, uint16_t and uint32_t, respectively
template<size_t Size>
using SizedUInt = std::conditional_t<Size == 8, uint8_t,
std::conditional_t<Size == 16, uint16_t,
std::conditional_t<Size == 32, uint32_t, void>>>;

template<size_t Size, typename T, size_t N>
SizedUInt<Size> read(const std::array<T, N>& arr, uint32_t adr)
{
SizedUInt<Size> returnValue{};
for (uint8_t i = 0; i <= sizeof(SizedUInt<Size>) - 1; ++i) {
returnValue <<= 8;
returnValue |= arr[adr + i];
}
return returnValue;
}

SizedUInt 是一个模板别名,它使用嵌套的 conditional_t 模板选择正确的类型。我已将最深的 conditional_t 的“false”类型设置为 void,以便在模板使用的值不同于 8、16 或 32 时触发编译错误.


或者,你可以这样做,使用你的模板类:

// create a temporary of type Read<32> and call its call operator
auto val = Read<32>{}(memory, 0);

关于c++ - 用模板化函数替换仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50657090/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com