c++ - 模板可以决定 C++ 中参数的数量吗?

标签 c++ templates

<分区>

考虑这样一个类

template<int n, class T>
class dimArray {
    T* arr;
    int len[n];
public:
    dimArray(int len₀, int len₁, int len₂, ..., int lenₕ₋₁, T initValue);
    T& at(int x₀, int x₁, int x₂, ..., int xₕ₋₁);
    void foo(int x₀, int x₁, int x₂, ..., int xₕ₋₁, .../*va_args*/);
}

被使用

dimArray<2, double> a(3,4, 1.0);
a.at(1,2) = 4.3;
std::cout << a.at(2,3);
a.foo(1,2, 7.3,4.2,0);

len₀等都是p码。有可能用 C++ 做这样的事情吗?如果是,怎么办?

最佳答案

您可以使用可变参数模板和 std::index_sequence 实用程序来完成:

template <std::size_t I, typename T>
using always_t = T;

template<typename Seq, class T>
class dimArrayImpl;

template<std::size_t ... Is, class T>
class dimArrayImpl<std::index_sequence<Is...>, T>
{
    T* arr;
    int len[sizeof...(Is)];
public:
    dimArrayImpl(always_t<Is, int>... lens, T initValue);
    T& at(always_t<Is, int>... lens);
    void foo(always_t<Is, int>... lens, .../*va_args*/);
};

template<int n, class T>
using dimArray = dimArrayImpl<std::make_indexsequence<n>, T>;

关于c++ - 模板可以决定 C++ 中参数的数量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54059644/

相关文章:

c++ - 接收 PCap 库问题

c++ - 模板化检查是否存在类成员函数?

未找到匹配的 C++ 模板运算符

python - Flask api 中的自定义静态路径?

javascript - Angular 2 将 HTML 注入(inject)内联模板

c++ - "using"关键字在 C++ 中究竟做了什么?

c++ - CMake:带有 PRE_BUILD 的 add_custom_command 不起作用

c++ - 延迟加载的 DLL - 我错过了什么?

c++ - 无法使用 Boost 正则表达式构建

c++ - 依赖类型 : Template argument deduction failed