【问题标题】:Evaluation of cout if it has a constexpr value?评估 cout 是否具有 constexpr 值?
【发布时间】:2015-06-21 07:00:46
【问题描述】:
#include <iostream>

class dummy{
public:
    constexpr
        dummy(int one, int two) noexcept
        :x(one),y(two){
    }


    constexpr int getX() noexcept{
        return x;
    }

    constexpr int gety() noexcept{
        return y;
    }

    constexpr int operator+(const dummy& asd){
        return (this->getX() + asd.getX() + this->gety() + asd.gety()) ;
    }

private:
    int x;
    int y;
};


int main(){
    constexpr dummy d1(2,4);
    constexpr dummy d2(2,4);

    int rand = 10;
    std::cout<<d1+d2<<std::endl;

    return 0;
}

据我了解,如果函数声明为 constexpr 并且采用 constexpr 值,则可以在编译时对其进行评估。

问题:

从这一行开始,std::cout&lt;&lt;d1+d2&lt;&lt;std::endl; 因为d1 + d2 是一个 constexpr 而 cout 运算符不是。 d1+d2 会在编译时进行评估吗?周围的cout 会发生什么?我很担心里面发生了什么。

【问题讨论】:

  • 输出结果基本上等价于std::cout &lt;&lt; 12 &lt;&lt; std::endl;d1+d2的值可以在编译时计算出来,但当然字符'1''2'只能写入标准输出运行时。

标签: c++ c++11


【解决方案1】:

constexpr 是在编译时评估的,而不是在运行时评估的,正如您在问题中提到的那样。

因此,在您的示例中,以下语句在编译时进行评估并初始化 d1 和 d2。

constexpr dummy d1(2,4);
constexpr dummy d2(2,4);

在编译时,它将使用constexpr的运算符重载函数对d1d2进行求和

所以在运行时下面的语句打印表达式 d1+d2 在编译时已经计算的结果。

std::cout<<d1+d2<<std::endl;

【讨论】:

  • 所以就像cout 会在运行时等待?
猜你喜欢
  • 2019-08-12
  • 1970-01-01
  • 2017-06-27
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
相关资源
最近更新 更多