在模板元编程中使用List类型

dor*_*ron 3 c++ template-meta-programming

我有一个编码方案,我使用以下规则转换数字[0-9]:

0 - 3
1 - 7
2 - 2
3 - 4
4 - 1
5 - 8
6 - 9
7 - 0
8 - 5
9 - 6

因此,我可以使用以下数组进行正向查找
int forward[] = { 3,7,2,4,1,8,9,0,5,6}
,其中forward[n]n的编码.类似地,以下用于逆查找
int inverse{ 7,4,2,0,3,8,9,1,5,6};
,其中`inverse [n]将解码n

在运行时可以很容易地从正向数组创建逆数组,但理想情况下,我想在编译时创建它.鉴于模板元编程是一种函数式语言,我首先使用以下方法在Haskell中实现了所有内容:

pos :: [Int] -> Int -> Int
pos lst x = 
    let 
        pos'::[Int] -> Int -> Int -> Int
        pos' (l:lst) x acc
            | l == x = acc
            | lst == [] = -1
            | otherwise = pos' lst x (acc + 1)
    in
        pos' lst x 0

inverse ::[Int] -> [Int]
inverse lst =
    let
        inverse'::[Int] -> Int -> [Int]
        inverse' l c 
            | c == 10 = []
            | otherwise = pos l c : inverse' l (c + 1)
    in
        inverse' lst 0 
Run Code Online (Sandbox Code Playgroud)

我设法pos使用以下方法在C++模板元编程中实现:

#include <iostream>

static int nums[] = {3,7,2,4,1,8,9,0,5,6};

template <int...>
struct pos_;

template <int Find, int N, int Arr0, int... Arr>
struct pos_<Find,N, Arr0, Arr...> {
    static constexpr int value = pos_<Find, N+1, Arr...>::value;
};

template <int Find, int N, int... Arr>
struct pos_<Find ,N, Find, Arr...> {
    static constexpr int value = N;
};

template <int Find,int N>
struct pos_<Find ,N> {
    static constexpr int value = -1;
};

template <int Find, int... Arr>
struct pos {
    static constexpr int value = pos_<Find,0, Arr...>::value;
};

int main()
{
    std::cout << "the positions are ";

    std::cout << pos<3, 3,7,2,4,1,8,9,0,5,6>::value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但是我在将数组转换为参数包时遇到问题,而在实现反向时,我无法分配value给参数包.

在模板元编程中使用列表的最佳方法是什么?

对于上下文,在查看Base64编码时会想到这个问题,我想知道是否有一种编译时生成反向编码的方法.

Dan*_* M. 5

在编译时生成逆数组的最简单/最简洁的方法是编写constexpr反函数.沿着:

template<size_t N>
constexpr std::array<int, N> inverse(const std::array<int, N> &a) {
    std::array<int, N> inv{};
    for (int i = 0; i < N; ++i) {
        inv[a[i]] = i;
    }
    return inv;
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到它:https://godbolt.org/g/uECeie

如果你想要更接近初始方法/ Haskell的东西,你可以查看如何使用TMP实现编译时列表以及如何为它们编写熟悉的函数(如append和concat).在那之后实施逆变得变得微不足道.顺便说一下,忽略了一般的C++语法铮铮,这些定义在精神上与你在函数式语言中找到的非常相似.