std :: declval< T>()如何工作? [英] How does std::declval<T>() work?
问题描述
我试图了解 std :: declval< T>()
的工作方式。我知道如何使用它,并且知道它的作用,主要是允许您使用 decltype
而不构造对象,例如
I am trying to understand how std::declval<T>()
works. I know how to use it, and know what it does, mainly allows you to use decltype
without constructing the object, like
decltype(std::declval<Foo>().some_func()) my_type; // no construction of Foo
我从 cppreference.com 表示 std :: declval< Foo>
添加一个右值对 Foo
的引用,由于引用折叠规则,该引用最终成为右值引用或左值引用。我的问题是为什么不调用 Foo
的构造函数?如何在不构造模板参数的情况下实现 std :: declval< T>
的玩具版本?
I know from cppreference.com that std::declval<Foo>
"adds" a rvalue reference to Foo
, which due to reference collapsing rules ends up being either a rvalue reference or a lvalue reference. My question is why the constructor of Foo
is not called? How can one implement a "toy" version of std::declval<T>
without constructing the template parameter?
PS:我知道它与旧的把戏不同
PS: I know it is not the same as the old trick
(*(T*)(nullptr))
推荐答案
基本上,在 sizeof
或 decltype
表达式中,您可以调用以下函数:没有在任何地方实现(它们需要声明,没有实现)。
Basically, in a sizeof
or decltype
expression you can call functions that aren't implemented anywhere (they need to be declared, not implemented).
例如
class Silly { private: Silly( Silly const& ) = delete; };
auto foo() -> Silly&&;
auto main() -> int
{
sizeof( foo() );
}
链接程序不应该对此抱怨。
The linker should not complain about that.
这篇关于std :: declval< T>()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!