get return type of function

Hi,

Say I have overloaded functions with different arguments AND return types. Each set of argument has only one corresponding return type.

Code:

`Vector grad(Scalar)`

Tensor grad(Vector)

Later I have:

Code:

`template <class T>`

void test(T x) {

... Y = grad(x)

}

Then how do I automatically declare the type of Y. Do I need to make the grad function a template and specialize each of them ?

Thanks for any help

Re: get return type of function

in c++11, you can simply write

"auto Y = grad(x);"

"auto const& Y = grad(x);"

...

or

"typedef decltype(grad(x)) GradType;

GradType Y = grad(x);"

etc... depending on what's the expected type of Y.

with c++2003 compilers, things get more complex ...

Re: get return type of function

Thanks a lot.

Unfortunately I am not using c++11 so I can not use those solutions.

I get 'error C3861: 'decltype': identifier not found' for the second solution.

Do you have the solution that works for in Visual studio 2008?

I appreciate your help.

Re: get return type of function

the easiest way is to write a trait class

Code:

`template <class T>`

struct grad_type {};

template <>

struct grad_type<Scalar> { typedef Vector type; };

template <>

struct grad_type<Vector> { typedef Tensor type; };

template <class T>

void test(T x) {

typename grad_type<Y>::type Y = grad(x)

}

of course, you need to specialize the trait for each possible parameter type. It would be easier if Scalar,Vector,Tensor had some high-level info in them ( like a rank grading ), in this way the trait could compute the grad_type automatically at compile time.

Anyway, I think emulating "auto"/"decltype" is possible in this case via some template machinery like SFINAE, but I wouldn't advise it if you don't know what you're doing ...

moreover, another simple solution could be to refactor the code, if possible; something like

Code:

`template <class T,class G>`

void test_impl(T& x,G y) {

// ...

}

template <class T>

void test(T x) {

test_impl( x, grad(x) );

}

Re: get return type of function

You are a life saver. I will use the traits method for now.

Scalar,vector and tensor are 1st,2nd and 3rd rank tensors but they are of completely different types represented by

double, double[], and double[][]. So I don't think I can automatically compute them. But anyway it is important to know

the higher or lower ranks in many places of the code so I will use that.

Thanks again.