枚举值作为 gsl::multi_span 的索引

enum value as index of gsl::multi_span

我想使用 enum 来访问 gsl::multi_span 中的元素。它适用于 int,所以我认为它适用于 enum 值,因为基础类型也是 int

#include <gsl/multi_span>
#include <iostream>

int main(int argc, char *argv[]) {
  const auto NUMBER_OF_PARAMS{2};
  if (argc != NUMBER_OF_PARAMS) {
    return -1;
  }

  enum param_index { PROG_NAME = 0, PARAM1 };
  const auto args = gsl::multi_span<char *>(argv, argc);

  // compiles
  std::cout << "Program name: " << args[0] << '\n';
  std::cout << "Parameter: " << args[1] << '\n';

  // does not compile
  std::cout << "Program name: " << args[param_index::PROG_NAME] << '\n';
  std::cout << "Parameter: " << args[param_index::PARAM1] << '\n';
}

GCC 版本 7 告诉我:

src/so.cpp:16:40: error: no match for ‘operator[]’ (operand types are ‘const gsl::multi_span<char*>’ and ‘main(int, char**)::param_index’)
   std::cout << "Program name: " << args[param_index::PROG_NAME] << '\n';
                                        ^
In file included from src/so.cpp:1:0:
./GSL/include/gsl/multi_span:1494:25: note: candidate: constexpr gsl::multi_span<ValueType, FirstDimension, RestDimensions>::reference gsl::multi_span<ValueType, FirstDimension, RestDimensions>::operator[](const index_type&) const [with ValueType = char*; long int FirstDimension = -1; long int ...RestDimensions = {}; gsl::multi_span<ValueType, FirstDimension, RestDimensions>::reference = char*&; gsl::multi_span<ValueType, FirstDimension, RestDimensions>::index_type = gsl::index<1>]
     constexpr reference operator[](const index_type& idx) const GSL_NOEXCEPT
                         ^~~~~~~~
./GSL/include/gsl/multi_span:1494:25: note:   no known conversion for argument 1 from ‘main(int, char**)::param_index’ to ‘const index_type& {aka const gsl::index<1>&}’
./GSL/include/gsl/multi_span:1500:19: note: candidate: template<bool Enabled, class Ret> constexpr Ret gsl::multi_span<ValueType, FirstDimension, RestDimensions>::operator[](gsl::multi_span<ValueType, FirstDimension, RestDimensions>::size_type) const [with bool Enabled = Enabled; Ret = Ret; ValueType = char*; long int FirstDimension = -1; long int ...RestDimensions = {}]
     constexpr Ret operator[](size_type idx) const GSL_NOEXCEPT
                   ^~~~~~~~
./GSL/include/gsl/multi_span:1500:19: note:   template argument deduction/substitution failed:

谁能解释一下为什么在这种情况下模板参数推导失败?有解决方法吗?

原因很简单。 gsl::index 是一种类型,如果其类型满足 details::are_integral, or if the type satisfies std::is_integral,则只能用值进行复制初始化。这适用于 int,但不适用于枚举。您需要使用 static_cast,例如:

static_cast<int>(param_index::PROG_NAME)