c++ - 类方法类型的 decltype

标签 c++ decltype

我想将类成员函数的返回值存储在另一个类中。

这似乎可行:

class Foo
{
public: 
   Foo(int) {} //non default constructor that hides default constructor
   unspecified_return_type get_value();


};

class Bar
{
    // stores a value returned by Foo::get_value
    decltype(Foo().get_value()) value;
};

然而,有一个对类 Foo 的默认构造函数的引用,在某些情况下可能未定义。有没有办法在不显式引用任何构造函数的情况下做到这一点?

最佳答案

是的,有。 std::declval正是出于这个原因而引入的(不需要依赖特定的构造函数):

decltype(std::declval<Foo>().get_value()) value;

关于c++ - 类方法类型的 decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25621179/

相关文章:

c++ - 为 Windows 提供带有时间函数的 srand()

c++ - C 等效于 C++ decltype

c++ - gcc 4.7 关于 Variadic Templates/decltype/std::forward

c++ - 如何在 C++11 中使用 decltype 引用当前类?

c++ - 当类型包含具有给定名称和类型的静态变量时启用_if 函数

c++ - 为什么要在堆中创建全局对象?

c++ - 通过模板从字符 ID 映射到 C++ 中的类名?

c++ - 初始化列表: cannot convert ‘Participant’ to ‘unsigned int’ in initialization

c++ - QVector 与 QList

c++ - 对这个 decltype 语句实际发生的事情感到困惑