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
254 views
in Technique[技术] by (71.8m points)

c++ - Extract the return type of a function without calling it (using templates?)

I'm looking for a way in C++ to extract the return type of a function (without calling it). I presume this will require some template magic.

float Foo();
int Bar();

magic_template<Foo>::type var1; // Here 'var1' should be of type 'float'
magic_template<Bar>::type var2; // and 'var2' should be of type 'int'

I am currently investigating how magic_template might be implemented, but have not found a solution so far.

Any ideas?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Take a look at boost type traits library, in particular the function_traits template provides such functionality out of the box. If you cannot use boost, just download the code and read the sources for some insight into how it is done.

Note that the functionality is based on types, not concrete functions, so you might need to add some extra code there.


After doing some small tests, this might not be what you really need, and if it is the 'some extra code' will be non-trivial. The problem is that the function_traits template works on function signatures and not actual function pointers, so the problem has changed from 'get the return type from a function pointer' to 'get the signature from a function pointer' which is probably the hardest part there.


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

...