我想使用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
,或者类型满足std::is_integral
,则只能使用值进行复制初始化。这对int
来说是正确的,但对于枚举则不然。您需要使用static_cast
,例如:
static_cast<int>(param_index::PROG_NAME)