c++ - 元组的可变参数生成

标签 c++ templates c++11

我想编写一个基于整数值和协调的 C++ 代码,生成一组元组和函数调用,如下所示:

// dimension = 1, input = (i) generated tuples: (i-1) (i), (i+1)
// dimension = 2, input = (i,j) generated tuples: (i-1, j), (i, j-1), (i, j),(i+1, j), (i, j+1)
<typename Index, int dimension>
void my_function(Index input)
{
    // some magic here that generates the following code or sth like this
    get_value(generated_tuple0);
    get_value(generated_tuple1);
    ....
    ....
    get_value(generated_tupleN);

}

我不擅长模板编程,也许使用 C++11 中的变量是可能的。

最佳答案

假设索引是一个元组,这是一个可能的解决方案:

template <class Index, int I, int dimension>
struct tuple_builder_t
{
    static void build(std::vector<Index> &result, Index center)
    {
        Index iter = center;
        for (int i = -1; i < 2; i++)
        {
            std::get<I - 1>(iter) = std::get<I - 1>(center) +i;
            tuple_builder_t<Index, I, dimension>::build(result,  iter);
        }
    }
};

template <class Index, int dimension>
struct tuple_builder_t<Index, dimension, dimension>
{
    static std::vector<Index> build(std::vector<Index> &result, Index center)
    {
        Index iter = center;
        for (int i = -1; i < 2; i++)
        {
            std::get<dimension - 1>(iter) = std::get<dimension - 1>(center) +i;
            result.push_back(iter);
        }
    }
};

template <class Index, int dimension>
void my_function(Index index)
{
    std::vector<Index> result;
    tuple_builder_t<Index, 1, dimension>::build(result, index);
}

这是一个很好的问题,我已经发现自己遇到了类似的问题(迭代超立方体的维度)

关于c++ - 元组的可变参数生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771398/

相关文章:

c++ - 将cv::Mat转换为std::vector的泛型函数

c++ - placement new 基于模板 sizeof()

C++ boost 模板参数特征

c++ - 用数字对 std::strings 进行排序?

c++ - 链接问题,C++ 成员函数到 C 回调

python - {{ 请求 }} var 空

c++ - 如何让所有平台编译器为 NaN 输出相同的字符串?

使用 CodeSynthesis XSD 树映射的 C++ 类型

c++ - 在另一个类中访问静态常量。

c++ - 为什么模板实例化永远在这里进行?