Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

c++ - How to use decltype with member functions

I'm trying to use decltype on member functions in Visual Studio 2012. I've stumbled upon a peculiarity and I'm wondering if this is intention or if it is a compiler bug. Consider (just a code snippet without meaning to show my point):

struct Test { int f() {return 0;} } T;
std::integral_constant<decltype(T.f()), 5>;
std::integral_constant<decltype(&Test::f), 5>; // error C2440

While the second line compiles, the third gives an error C2440: 'specialization' : cannot convert from 'int' to 'int (__thiscall Test::*)(void)'

How come decltype on an instanciated call to a function yields its return type (this is what I am expecting), however trying to do the same without any member involved does yield a member function pointer? If this is the intended behavior, what is the reasoning behind it? How would I denote that I'm requesting the return type of a member function, without actually having an instance at hand? Of course I could do it the dirty way:

std::integral_constant<decltype(((Test*)nullptr)->f()), 5>;

But unquestionable this is pretty, pretty ugly and there should be a clean, straightforward C++ way to express this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

&Test::f does not call the member function Test::f. Instead, it takes the address of the member function and results in a pointer to member function, which is of type int (Test::*)().

In order to do what you want, you should use std::declval. The correct syntax is

std::integral_constant<decltype(std::declval<Test>().f()), 5>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...