gpt4 book ai didi

c++ - 使用 decltype 理解类型推导

转载 作者:太空狗 更新时间:2023-10-29 20:51:44 24 4
gpt4 key购买 nike

考虑以下 C++ 代码:

#include <bits/stdc++.h>

template <typename T> void print_type() { std::cout << __PRETTY_FUNCTION__ << std::endl; }

class Base{
int num;
public:
Base() : num{0} {}

friend std::ostream & operator << ( std::ostream& stream, Base & obiekt){
stream<< "num: " << obiekt.num;
return stream;
}
};

int main(){
Base a{};
std::cout << a << std::endl;
std::cout << "type of a: " << std::endl;
print_type < decltype( a ) > ();

std::cout << "type of (a): " << std::endl;
print_type < decltype( (a) ) > ();


Base b();
std::cout << b << std::endl;

std::cout << "type of b: " << std::endl;
print_type < decltype( b ) > ();

std::cout << "type of (b): " << std::endl;
print_type < decltype( (b) ) > ();


return 0;
}

我用 g++ 7.2.0 编译它,得到如下输出:

num: 0
type of a:
void print_type() [with T = Base]
type of (a):
void print_type() [with T = Base&]
1
type of b:
void print_type() [with T = Base()]
type of (b):
void print_type() [with T = Base (&)()]

我的问题:

  • 为什么 std::cout << b << std::endl;打印“1”?
  • 什么是类似 Base() 的类型或 Base (&)()
  • 为什么输入 (a)Base& , 当 a类型为 Base

我正在寻找答案,但找不到。我知道在这种情况下我应该使用像 Base a; 这样的声明没有任何括号,但我想知道 Base a; 之间的区别, Base a{};Base a(); .为什么它在没有任何警告或错误的情况下编译?感谢您的帮助。

最佳答案

主要问题是:

Base b();

并没有按照你的想法去做。事实上,它是一个接受零参数并返回 Base 类型对象的函数声明。


Why std::cout << b << std::endl; prints "1"?

因为b是一个指向函数的指针。结果,过载:

basic_ostream& operator<<( bool value );

被使用并且 1 被打印为指向函数的指针永远不会为空。

一个更有趣的问题是为什么 gcc 甚至接受代码并只产生警告。函数 b 没有定义,只有它的声明,所以我希望代码不会链接。


What is a type like Base() or Base (&)()?

Base() 是一个指向函数的指针,不接受参数并返回 BaseBase (&)() 是对相同的功能。


Why type of (a) is Base&, when a has type Base?

因为decltype works so :

decltype(expression)

If the argument is an unparenthesized id-expression or an unparenthesized class member access expression, then decltype yields the type of the entity named by this expression. If there is no such entity, or if the argument names a set of overloaded functions, the program is ill-formed.

If the argument is any other expression of type T, and

a) if the value category of expression is xvalue, then decltype yields T&&;

b) if the value category of expression is lvalue, then decltype yields T&;

c) if the value category of expression is prvalue, then decltype yields T.

关于c++ - 使用 decltype 理解类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601830/

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