gpt4 book ai didi

c++ - void()、逗号运算符 (operator,) 和不可能的 (?) 重载

转载 作者:IT老高 更新时间:2023-10-28 22:03:00 26 4
gpt4 key购买 nike

考虑以下结构:

struct S {};

在 C++14 中,下面的定义是有效的:

constexpr auto f() { return S{}, 'c'; }

还有下面这个:

constexpr auto f() { return S{}, void(); }

现在,考虑以下涉及两个定义中的第一个的工作片段:

#include<type_traits>

struct S {};

constexpr int operator,(S, char) { return 42; }
constexpr auto f() { return S{}, 'c'; }

int main() {
constexpr int i{f()};
static_assert(i == 42, "!");
static_assert(std::is_same<decltype(f()), int>::value, "!");
}

从技术上讲,逗号运算符的过载拦截这对夫妇S{}, 'c'并返回一个整数,正如 main 中正确验证的那样功能。

现在,假设我想对 f 的第二个定义做同样的事情:

constexpr auto f() { return S{}, void(); }

在这种情况下,逗号运算符应该截取 S{}, void() 的形式.
以下定义都不起作用(原因很明显):

constexpr int operator,(S, void) { return 42; }

下面的也不是(在前一种情况下会起作用):

template<typename T> constexpr int operator,(S, T &&) { return 42; }

有没有什么办法可以重载逗号操作符来处理S{}, void() ?
否则不是标准中的缺失吗,因为它允许以这种方式使用逗号运算符,但不会让您有机会重载相同的运算符(即使 the standard mentions that overloaded functions involving S are allowed )?


注意:这个问题是出于好奇而提出的。请避免像不要那样做这不是好的做法这样的评论。我不打算在生产环境中这样做。谢谢。

最佳答案

与此相关的子句是 N4140 中的 13.3.1.2/9 [over.match.oper]:

If the operator is the operator ,, the unary operator &, or the operator ->, and there are no viable functions, then the operator is assumed to be the built-in operator and interpreted according to Clause 5.

由于 void() 永远不是有效的函数参数(参见 5.2.2/7 [expr.call]),因此永远不存在可行的函数,因此内置 将被使用。

所以不,您尝试做的事情是不可能的。

其实就是这样写一个迭代器循环

for(...; ++it1, (void)++it2)

是通过强制使用内置运算符 , 为迭代器类型重载 , 来防止用户破坏代码的标准方法。 (请注意,我并不是说您需要在日常代码中执行此操作。这在很大程度上取决于其实际使用情况。这是偏执狂的标准库级别。)


关于您链接的标准条款:

The meaning of the operators =, (unary) &, and , (comma), predefined for each type, can be changed for specific class and enumeration types by defining operator functions that implement these operators.

但是不能定义这样的函数,因为正如我上面所说,void() 永远不是有效的函数参数。

现在这是否是标准中的疏忽/问题尚有待商榷。

关于c++ - void()、逗号运算符 (operator,) 和不可能的 (?) 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39514765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com