Get return type of member function without an object

James picture James · Apr 7, 2011 · Viewed 14.8k times · Source

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?

Answer

Puppy picture Puppy · Apr 7, 2011

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;