类方法类型的decltype

qua*_*ell 7 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;
};
Run Code Online (Sandbox Code Playgroud)

但是,有一个类Foo的默认构造函数的引用,在某些情况下可能没有定义.有没有办法在没有明确引用任何构造函数的情况下执行此操作?

jro*_*rok 9

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

decltype(std::declval<Foo>().get_value()) value;
Run Code Online (Sandbox Code Playgroud)

  • @MarcoA.没有优化.`decltype`是一个未评估的上下文(expresions仅针对其类型进行评估,但不是实际执行的). (2认同)

101*_*010 5

您可以借助std::declval以下示例来完成此操作:

#include <iostream>
#include <utility>

struct test {
  int val = 10;
};

class Foo {
public:
   test get_value() { return test(); }
};

class Bar {
public:
  using type = decltype(std::declval<Foo>().get_value());
};

int main() {
  Bar::type v;
  std::cout << v.val << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

LIVE DEMO

std::declval<T>将任何类型 T 转换为引用类型,从而可以在decltype表达式中使用成员函数,而无需通过构造函数。

std::declval通常用在模板中,可接受的模板参数可能没有共同的构造函数,但具有需要返回类型的相同成员函数。