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

c++ - Get return type of member function without an object

I have a number of classes that I cannot modify. Each has a copy constructor, at least one other constructor, and a function foo() that returns some value. I want to make a class template that can derive from each of these classes, and has a data member that is the same type as the return type of foo() (sorry if I've got some of the terminology wrong).

In other words, I would like a class template

template<typename T> class C : public T
{
  footype fooresult;
};

where footype is the return type of T::foo().

If the base classes all had, say, a default constructor, I could do

decltype(T().foo()) fooresult;

(with the C++0x functionality in GCC) but the classes don't have any particular constructor in common, apart from the copy constructors.

GCC also doesn't allow decltype(this->foo()), though apparently there is a possibility that this will be added to the C++0x standard - does anyone know how likely that is?

I feel like it should be possible to do something along the lines of decltype(foo()) or decltype(T::foo()) but those don't seem to work: GCC gives an error of the form cannot call member function 'int A::foo()' without object.

Of course, I could have an extra template parameter footype, or even a non-class parameter of type T, but is there any way of avoiding this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You don't need that- remember that since decltype doesn't evaluate its argument, you can just call on nullptr.

decltype(((T*)nullptr)->foo()) footype;

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

...