小编use*_*188的帖子

c ++ 11 constexpr将std :: array的列表展平为数组

我开始使用c ++ 11,constexpr和模板元编程似乎是一种在微型微控制器上保存稀缺内存的好方法.

有没有办法编写模板来展平constexpr数组列表,我需要的是一种方法:

constexpr std::array<int, 3> a1 = {1,2,3};
constexpr std::array<int, 2> a2 = {4,5};
constexpr auto a3 = make_flattened_array (a1,a2);
Run Code Online (Sandbox Code Playgroud)

我使用gcc 4.8.4(arm-none-eabi),如果需要,可以使用std = c ++ 11或c ++ 1y选项进行编译.

c++ arrays std constexpr c++11

19
推荐指数
2
解决办法
5374
查看次数

如何编写constexpr函数来操作转发的参考元组?

我编写了一个constexpr函数,用于计算元组元素大小的总和.

直接调用时,函数调用将使用值元组和引用元组进行编译.

当通过模板化函数调用时,它仍然使用值元组编译,但是使用引用元组失败.

我可以使用指针元组而不是参考元组来解决我的问题,但我写的东西的API(一组模板化的功能,以便于为微控制器编写SPI和I²C驱动程序)将不那么干净.

谢谢你的帮助.

Ps:我正在使用gcc8.2使用c ++ 17标准.

亚历山大

#include <tuple>

template <typename> struct is_tuple_t: std::false_type {};
template <typename ...T> struct is_tuple_t<std::tuple<T...>> : std::true_type {};

template<typename Type>
constexpr bool is_tuple(const Type&) {
    if constexpr (is_tuple_t<Type>::value) 
        return true;
    else
        return false;
}

template<class F, class...Ts, std::size_t...Is>
constexpr void for_each_in_tuple(const std::tuple<Ts...> & tupl, F func,
             std::index_sequence<Is...>){
    using expander = int[];
    (void)expander { 0, ((void)func(std::get<Is>(tupl)), 0)... };
}

template<class F, class...Ts>
constexpr void for_each_in_tuple(const std::tuple<Ts...> & tupl, F func){
    for_each_in_tuple(tupl, func, std::make_index_sequence<sizeof...(Ts)>());
} …
Run Code Online (Sandbox Code Playgroud)

c++ c++17

5
推荐指数
1
解决办法
160
查看次数

标签 统计

c++ ×2

arrays ×1

c++11 ×1

c++17 ×1

constexpr ×1

std ×1