类方法类型的decltype
decltype for class method type
我想将类成员函数的返回值存储在另一个类中。
这似乎奏效了:
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
通常用于可接受的模板参数可能没有公共构造函数,但具有需要返回类型的相同成员函数的模板中。
相关文章:
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 是否可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型
- c++ 11 带有 decltype 的尾随返回类型无法按预期工作
- 我可以使用 decltype() 或其他东西通过指针获取真实类型吗?
- 来自 decltype 的意外输出类型
- 有条件地选择带有 decltype() 和三元运算符的类型
- 为什么在 ctor 的参数列表中将成员"x"的类型替换为"decltype(x)"会破坏类模板参数推导?
- C++中的可视化 Decltype 表达式类型推导
- 不完整类型的调用运算符的 decltype 的特殊行为
- decltype(auto) 是否使尾随返回类型过时?
- 用 decltype 和 auto 推导出 const(返回)类型
- 元函数使用 decltype 返回元素类型
- 不同类型的"decltype((const int)a)"和"decltype((cons
- 关于 C++ 中面向对象中的 decltype 类型
- 使用“decltype”获取迭代器的类型
- 如何使用非尾随 decltype 返回类型定义行外类模板成员函数
- clang 拒绝具有尾随 decltype 返回类型的模板调用是否正确,具体取决于其重载之一?
- 尾随返回类型中去 decltype 的原因
- decltype(function_name) 的返回类型是完全无用的
- 如何通过扩展以下类型特征来删除 decltype(&MyClass::funct) 部分?