【问题标题】:Can template decide the number of arguments in C++? [duplicate]模板可以决定 C++ 中参数的数量吗? [复制]
【发布时间】:2019-01-06 16:05:04
【问题描述】:

考虑这样一个类

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++ 做这样的事情吗?如果有,怎么做?

【问题讨论】:

标签: c++ templates


【解决方案1】:

您可以使用可变参数模板和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++14 的吗?
  • std::index_sequence确实是c++14,但是可以用C++11实现。可变参数模板来自 C++11。要在 C++98 中“模拟”它,您必须编写多达 N 个特化,(每个版本大多重复代码)或使用具有特殊类型的固定数字...
猜你喜欢
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多