Infix vs前缀语法:名称查找差异 [英] Infix vs prefix syntax: name lookup differences
问题描述
C ++中的运算符通常被认为是函数/方法的替代语法,特别是在重载的上下文中。如果是这样,下面的两个表达式应该是同义词:
Operators in C++ are usually considered to be an alternative syntax for functions/methods, especially in the context of overloading. If so, the two expressions below should be synonymous:
std::cout << 42;
operator<<(std::cout, 42);
实际上,第二个语句会导致以下错误: p>
In practise, the second statement leads to the following error:
call of overloaded ‘operator<<(std::ostream&, int)’ is ambiguous
像往常一样,此类错误消息附有可能的候选列表,其中包括:
As usual, such error message is accompanied with a list of possible candidates, these are:
operator<<(basic_ostream<_CharT, _Traits>& __out, char __c)
operator<<(basic_ostream<char, _Traits>& __out, char __c)
operator<<(basic_ostream<char, _Traits>& __out, signed char __c)
operator<<(basic_ostream<char, _Traits>& __out, unsigned char __c)
此错误至少会产生两个问题:
Such error raises at least two questions:
- 为什么
运算符<<(basic_ostream< char ,_Traits>& __out,
int
__ c)
缺少?
- In what way are the two statements different (in terms of name lookup)?
- Why
operator<<(basic_ostream<char, _Traits>& __out,
int
__c)
is missing?
看来,中缀和前缀符号不能完全互换 - 不同的语法需要不同的名称解析策略。
It seems, that infix and prefix notations are not fully interchangeable -- different syntax entails different name resolution tactics. What are the differences and where did they come from?
推荐答案
不,这两个表达式不应该是同义词。 std :: cout<< 42
被查找为运算符<<<(std :: cout,42)
和 std :: cout。 operator<<(42)
。这两个查找产生可行的候选人,但第二个是更好的匹配。
No, the two expressions should not be synonymous. std::cout << 42
is looked up as both operator<<(std::cout, 42)
and std::cout.operator<<(42)
. Both lookups produce viable candidates, but the second one is a better match.
这篇关于Infix vs前缀语法:名称查找差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!