【发布时间】:2021-12-01 00:30:53
【问题描述】:
template <typename CRTP>
struct Pre {
CRTP & operator++();
};
template <typename CRTP>
struct Post {
CRTP operator++(int);
};
struct Derived
: Pre<Derived>
, Post<Derived>
{};
int main() {
Derived d;
d++;
++d;
}
我从 GCC 收到这些错误:
<source>: In function 'int main()':
<source>:18:10: error: request for member 'operator++' is ambiguous
d++;
^~
<source>:8:14: note: candidates are: CRTP Post<CRTP>::operator++(int) [with CRTP = Derived]
CRTP operator++(int);
^~~~~~~~
<source>:3:16: note: CRTP& Pre<CRTP>::operator++() [with CRTP = Derived]
CRTP & operator++();
^~~~~~~~
<source>:19:11: error: request for member 'operator++' is ambiguous
++d;
^
<source>:8:14: note: candidates are: CRTP Post<CRTP>::operator++(int) [with CRTP = Derived]
CRTP operator++(int);
^~~~~~~~
<source>:3:16: note: CRTP& Pre<CRTP>::operator++() [with CRTP = Derived]
CRTP & operator++();
^~~~~~~~
前减和后减运算符会导致类似的错误。 Clang 没有这样的错误。有什么想法可能是错误的或如何解决这个问题?
【问题讨论】:
-
using Pre::operator++; using Post::operator++;有效,但我想它违背了您的 CRTP 的目的...... -
fwiw 也提供了实现,也没有 crtp gcc reports the error
-
@Quentin 将 using 声明放入帮助模板
PrePost : Pre, Post -
对我来说 gcc 的行为似乎是正确的。函数
operator ++的调用不应编译,因为不清楚名称operator ++指的是哪个函数。 -
从某种意义上说,语言本身存在需要解决的不一致问题,这并不是缺陷。如果你是的话,这只是一个带有不幸后果的设计选择,一个口语缺陷。
标签: c++ operator-overloading multiple-inheritance ambiguous