从成员函数指针获取方法的返回类型
Get the return type of a method from a member function pointer
我试图声明一个变量,使其类型与我有成员函数指针的成员函数的返回类型相同。
class Widget {
public:
std::chrono::milliseconds Foo();
};
例如给定指向CCD_ 2的成员函数指针CCD_,如何声明一个变量blah
,使其获得Widget::Foo
的返回类型(std::chrono::milliseconds
)?
我从一篇博客文章中找到了一些很有前景的指导,该文章使用了<type_traits>
中的result_of
和decltype
,但我似乎无法使其发挥作用。
auto fn = &Widget::Foo;
Widget w;
std::result_of<decltype((w.*fn)())>::type blah;
这种方法对我来说很有意义,但VC++2013不喜欢它。
C:Program Files (x86)Microsoft Visual Studio 12.0VCincludexrefwrap(58): error C2064: term does not evaluate to a function taking 0 arguments
C:Program Files (x86)Microsoft Visual Studio 12.0VCincludexrefwrap(118) : see reference to class template instantiation 'std::_Result_of<_Fty,>' being compiled
with
[
_Fty=std::chrono::milliseconds (__cdecl Widget::* )(void)
]
scratch.cpp(24) : see reference to class template instantiation 'std::result_of<std::chrono::milliseconds (__cdecl Widget::* (void))(void)>' being compiled
我不知道我是做错了什么,还是VC++还没有处理好这件事(或者两者都有!)。我在错误消息中看到的唯一线索是__cdecl
。呼叫约定不应该是fn
0吗?
decltype((w.*fn)()) blah;
或
std::result_of<decltype(fn)(Widget)>::type blah;
不知道它为什么与一起工作
std::result_of<decltype(fn)(Widget)>::type blah;
但我认为括号中应该有一个指向Widget的指针。因为第一个成员参数是隐藏的"this",指向对象的指针
std::result_of<decltype(fn)(Widget*)>::type blah;
class Widget
{
public:
virtual int foo() = 0;
};
int Widget::foo() { }
int main() {
// Your code goes here
auto fn = &Widget::foo;
std::result_of<decltype(fn)(Widget*)>::type blah = 5;
std::cout << blah;
return 0;
}
// output: 5
此外,我们不能创建抽象类的对象,所以代码不会编译,如果Widget是一个抽象类,而不是它的指针将在括号中
std::result_of<decltype(fn)(Widget)>::type blah = 5;
编译错误:
error: cannot declare parameter to be of abstract type 'Widget'
std::result_of<decltype(fn)(Widget)>::type blah = 5;//
error: incomplete type 'std::result_of<int (Widget::*(Widget))()>' used in nested name specifier
std::result_of<decltype(fn)(Widget)>::type blah = 5;//
相关文章:
- 我的模板类方法返回错误类型?
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 具有引用返回类型的重写方法上的协变返回类型无效
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- Java 调用 dll 字符串返回类型方法
- 必须使用尾随返回类型的示例,因为无法用旧方法解决问题
- 如何拥有两个名称相同但返回类型不同的纯虚拟方法
- 可能从单个方法返回不同类型的对象
- qml 未知方法返回类型:ArchiveFile*,即使调用了 qmlRegisterUncreatableType
- std::d eclval vs crtp,无法从不完整类型推断方法返回类型
- 将返回类型推断为模板参数类型方法
- dlsym() 解决方法返回类型
- 我如何根据某些模板参数影响模板类方法的返回类型
- 如何检查模板类方法返回类型
- 覆盖方法返回类型,在C 中使用不完整的派生类
- 类成员方法 - 返回类型模板
- C++中具有多态模板类的未知方法返回类型
- 是否可以使用Boost概念检查库验证方法返回类型
- 使用不同方法返回类型的C++模板类设计