【问题标题】:C++ concepts and std::coutC++ 概念和 std::cout
【发布时间】:2018-05-31 14:42:49
【问题描述】:

为了学习 C++ 概念,我尝试重新创建 EqualityComparable 概念。这是我写的代码

#include <iostream>

template<typename T>
concept bool EqualityComparable = requires(T a, T b) 
{
    {a == b};
    {a != b};
};


void foo(EqualityComparable a, EqualityComparable b)
{
    //auto t = a == b;
    //std::cout << t;  //Case 1 : This compiles
    std::cout << a == b; //Case 2 : This does not
}

int main()
{
    foo(4,2);
}

这个想法很简单,就是有一个函数 foo 有两个参数,支持运算符 ==!= 但是,当我使用时,我尝试在对 std::cout 的调用中直接比较 ab,我得到以下编译器错误

main.cpp: 在 'void foo(auto:1, auto:1) [with auto:1 = int]' 的实例化中: main.cpp:19:12:从这里需要 main.cpp:14:20: error: no match for 'operator==' (operand types are 'std::basic_ostream' and 'int')

正如我在评论中所说,如果我先比较 a 和 b 然后调用 std::cout 一切正常。所以我的问题是:为什么 gcc 将我的类型推断为std::basic_ostreamintin case 2? 我使用 coliru 编译带有以下参数的代码

g++ -std=c++1z -O2 -fconcepts -Wall -pedantic -pthread main.cpp && ./a.out

【问题讨论】:

  • std::cout &lt;&lt; (a == b); 因为运算符优先级等等
  • 哦,当然,我很傻

标签: c++ g++ c++17 c++-concepts


【解决方案1】:

因为运算符&lt;&lt;的优先级高于运算符==

Operator precedence

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2020-12-11
    • 1970-01-01
    • 2020-01-27
    • 2017-12-30
    • 1970-01-01
    相关资源
    最近更新 更多