【发布时间】:2016-03-07 10:36:32
【问题描述】:
C++ Core Guidelines推广using span的做法。
问题在于 const 和 mutable 范围。这是我试图做的:
auto foo(gsl::span<int>); // 1st
auto foo(gsl::span<const int>); // 2nd
但是如果没有明确的 span 参数的强制转换/构造,它们就不能被调用:
std::vector<int> v;
const std::vector<int> cv;
const std::vector<int>& crv = v;
// ambiguous
// want to call 1st
foo(v);
// ambiguous, although 1st is illegal (static_assert kicks in)
// want to call 2nd
foo(cv); // ambiguous
foo(crv); // ambiguous
处理这个问题的正确方法是什么?
这似乎应该是微不足道的,类似于 const T& 和 T& 重载,但它不是(或者我只是没看到)。
为了在同一页面上,foo(gsl::span<int>{v}) 很麻烦,我想避免它,让调用者简单:foo(v)。
我概括了这个问题,但万一这是一个 XY 问题,这就是我实际尝试做的:
auto split(gsl::cstring_span<> str) -> std::vector<gsl::cstring_span<>>;
auto split(gsl::string_span<> str) -> std::vector<gsl::string_span<>>;
并且希望可以使用[const] char *、[const] string 等参数调用。
【问题讨论】:
-
const std::vector< int >?确定吗?不应该是std::vector< const int >吗? -
@DevSolar 是的,这就是我的意思。想想
const std::vector<int>& crv = v。 -
@DevSolar 如果您考虑一下
string&和const string&,我认为会更清楚。 -
@DevSolar 好主意,但不起作用。编译器发出错误 C2338:C++ 标准禁止 const 元素的容器,因为 allocator
格式不正确。 . -
@WernerHenze:是的,那也是...我只是指出 OP 的第一个示例(
span<int>,span< const int >)与他的第二个示例(std::vector< int >,const std::vector< int >)不匹配) 意图。 (另外,神圣的死灵蝙蝠侠...... :-D)
标签: c++ c++14 cpp-core-guidelines