Search code examples
c++templatesc++11decltype

How do I get the return type of a 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++11 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?


Solution

  • 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;