我试图理解declval<T>()和declval<T&>()之间的区别吗?是否有一个T&可以使用而T不能使用的例子?
#include <type_traits>
#include <utility>
struct X {
X() = delete;
int func();
};
int main()
{
// works with both X as well as X& within declval
static_assert(std::is_same_v<decltype(std::declval<X&>().func()), int>);
}发布于 2021-08-22 19:59:46
除了ref限定的成员函数(很少使用)外,std::declval<T&>()更常见的用例是创建lvalue引用(否则会创建rvalue-引用)。
#include <type_traits>
#include <utility>
struct X {};
int func(X&);
int main() {
static_assert(std::is_same_v<decltype(func(std::declval<X&>())), int>); // works
static_assert(std::is_same_v<decltype(func(std::declval<X>())), int>); // error
}发布于 2021-08-22 19:48:07
是否有一个
T&可以使用而T不能使用的例子?
是的,例如,在这种情况下,您有ref限定的重载:
struct X {
X() = delete;
int func() &;
double func() &&;
};
int main() {
// this static_assert would fail:
static_assert(std::is_same_v<decltype(std::declval<X>().func()), int>);
}https://stackoverflow.com/questions/68884590
复制相似问题