Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 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 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...