Constexpr可变参数模板以对无符号整数重新排序

问题描述 投票:0回答:1

我正在与外设一起工作,该外设首先发送最低的8位字。因此,第一个字(在本例中为16bit)必须在右侧。如变量v1所示。

我想拥有一个更具表现力的版本,所以我想添加一个constexpr函数,该函数将第一个参数移到结果整数最右边的位置。仍将其用作函数的第一个参数。

我并没有真正提出一个好的解决方案。当我建立一个“移位值”并在离开递归时减小它。另外,这在constexpr环境中不起作用,对我来说这是“不行”。也许有人建议吗?

我确实做了很多尝试。但大多数情况下不起作用。折叠表达式也没有真正的帮助。Cpp版本无关紧要(c ++ 2a也可以)

// send 0x05 first then 0xFF
std::uint16_t v1 = (0xFFU << 8U | 0x05U); // right align first 8bit word so it is send first
std::uint16_t v2 = lower_word_first(0x05U, 0xFFU); 

// lower_word_first

static std::size_t shift = 0;

auto lower_word_first(){
    return 0;
}

template<typename unsigned_word_type, typename... words>
auto lower_word_first(unsigned_word_type word, words... ws){
    shift += 1;
    auto val = lower_word_first(ws...); // just for debugging purposes split into val
    auto res = val | word << (shift - 1) * 8U;
    shift -= 1;
    return res;
}
c++ variadic-templates
1个回答
0
投票
#include <cstddef>
#include <utility>

template <std::size_t... Is, typename... Ws>
constexpr auto lower_word_first(std::index_sequence<Is...>, Ws... ws)
{
    return ((ws << Is*8) | ...);
}

template <typename... Ws>
constexpr auto lower_word_first(Ws... ws)
{
    return lower_word_first(std::index_sequence_for<Ws...>{}, ws...);
}

DEMO

© www.soinside.com 2019 - 2024. All rights reserved.