类方法类型的decltype

decltype for class method type

本文关键字:decltype 类型 类方法      更新时间:2023-10-16

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

这似乎奏效了:

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;

您可以在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;
}

现场演示

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

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