c++ - 使用 constexpr 混淆 std::array

标签 c++ variadic-templates template-meta-programming constexpr stdarray

我正在寻找一个能够通过增加值来转换 std::array 的小函数。该函数必须是编译时函数。

我能够为长度为 3 的数组编写一个小的 constexpr 函数,但我无法将其概括为任意长度的 std::array。我也未能将其概括为包含不同于 char 的内容。

有人知道怎么做吗?

#include <array>
#include <iostream>
#include <valarray>

constexpr std::array<char,3> obfuscate(const std::array<char,3>& x)  {
     return std::array<char, 3>{x.at(0)+1, x.at(1) + 2, x.at(2) + 3 };
}

/* Won't compile

template<typename T,typename S, template<typename, typename> L=std::array<T, U>>
constexpr L<T,U> obfuscate(const L<T, U>& x) {
    return {x.at(0) + 1, x.at(0) + 2, x.at(0) + 3 };
}
*/

std::ostream& operator<<(std::ostream& str, const std::array<char, 3>& x) {
    for (auto i = 0; i < 3; i++) {
        str << x.at(i);
    }
    return str;
}

int main(int argc, char** args) {
    std::array<char, 3> x{ 'a','b','c' };
    std::cout << x << std::endl;
    std::cout << obfuscate(x) << std::endl;
//  std::cout << obfuscate<3>(x) << std::endl;
}

最佳答案

你可以使用std::index_sequence:

template<class T, std::size_t N, std::size_t... Is>
constexpr std::array<T, N> helper (const std::array<T, N> &x, std::index_sequence<Is...>) {
     return std::array<T, N>{static_cast<T>(x.at(Is)+Is+1)...};
}

template<class T, std::size_t N>
constexpr std::array<T, N> obfuscate(const std::array<T, N> &x) {
     return helper(x, std::make_index_sequence<N>{});
}

关于c++ - 使用 constexpr 混淆 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49317953/

相关文章:

c++ - 使用可变参数模板制作类似元组的编译时 "linked-list"

c++ - 在 C++ 中是否可以遍历抽象类的所有子类?

c++ - 为什么 C+ +'s ` 变量模板的行为不符合预期?

c++ - LNK2019/LNK2001错误: Why would a library provide a . cpp文件有未实现的功能? (它们如何实现?)

c++ - 检测动态分配的对象?

c++ - 比较 int 的正向和反向循环,其中一个限制为 0

c++ - 接受所有版本的 const/volatile 限定和 & vs && 的类模板特化

c++ - 无法在 Fedora 上连接冰淇淋 (icecc)

c++11 - 将参数包拆分为 0 ... N-1 和第 N 个元素

c++ - 为什么 C++ 函数参数包必须是占位符或包扩展?