Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 732
James Avatar asked Apr 07 '11 11:04

James


People also ask

What is the return type of member function?

Member Function Return Types. A public member function must never return a non-const reference or pointer to member data. A public member function must never return a non-const reference or pointer to data outside an object, unless the object shares the data with other objects.

What is Declval?

declval is commonly used in templates where acceptable template parameters may have no constructor in common, but have the same member function whose return type is needed.

Which type of function is not a member of a class?

Friend functions are actually not class member function. Friend functions are made to give private access to non-class functions. You can declare a global function as friend, or a member function of other class as friend.


1 Answers

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; 
like image 128
Puppy Avatar answered Sep 28 '22 02:09

Puppy