获取模板化对象方法的返回类型
Getting the Return Type of a Templatized Object's Method
说我有:
template <typename T>
struct Foo {
T& func();
};
我实现了一个Foo
: Foo<int> bar
现在我想得到bar.func()
的返回类型。我一直试图强迫result_of
和我一起工作,但无济于事。
我真正想要的是能够做result_of_t<foo.func>
并完成它,但我想这要困难得多?我应该如何获得这个返回类型?
我希望在不考虑bar
如何申报的情况下实现这一目标。也就是说,我只想将bar.func
传递给result_of
或类似的值,并输出返回类型。
std::result_of
实际上使用起来很烦人。它的语法是:
result_of<F(ArgTypes...)>
其中F
是可调用的东西,这里的所有东西都是类型。在您的示例中,您希望调用一个成员函数:&Foo<int>::func
。但是,您需要的不是指向成员的指针的值,而是类型。我们想要decltype(&Foo<int>::func)
。调用成员函数的方法是传递对象的实例作为第一个参数。
把它们放在一起,我们得到:
using T = std::result_of_t<decltype(&Foo<int>::func)(Foo<int>&)>;
static_assert(std::is_same<T, int&>::value, "!");
或者我们可以直接使用decltype
:
using T = decltype(std::declval<Foo<int>&>().func());
更自然。
给定bar
,这只是:
using T = decltype(bar.func());
相对于:
using T = std::result_of_t<decltype(&decltype(bar)::func)(decltype(bar))>;
相关文章:
- 我的模板类方法返回错误类型?
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 具有引用返回类型的重写方法上的协变返回类型无效
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- Java 调用 dll 字符串返回类型方法
- 必须使用尾随返回类型的示例,因为无法用旧方法解决问题
- 如何拥有两个名称相同但返回类型不同的纯虚拟方法
- 可能从单个方法返回不同类型的对象
- qml 未知方法返回类型:ArchiveFile*,即使调用了 qmlRegisterUncreatableType
- std::d eclval vs crtp,无法从不完整类型推断方法返回类型
- 将返回类型推断为模板参数类型方法
- dlsym() 解决方法返回类型
- 我如何根据某些模板参数影响模板类方法的返回类型
- 如何检查模板类方法返回类型
- 覆盖方法返回类型,在C 中使用不完整的派生类
- 类成员方法 - 返回类型模板
- C++中具有多态模板类的未知方法返回类型
- 是否可以使用Boost概念检查库验证方法返回类型
- 使用不同方法返回类型的C++模板类设计