
November 21st, 2012, 04:25 AM
#1
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

November 21st, 2012, 04:51 AM
#2
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 ...

November 21st, 2012, 05:05 AM
#3
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.
Last edited by dshawul; November 21st, 2012 at 05:13 AM.

November 21st, 2012, 05:50 AM
#4
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 highlevel 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) );
}

November 21st, 2012, 06:46 AM
#5
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.
Last edited by dshawul; November 21st, 2012 at 06:48 AM.
Posting Permissions
 You may not post new threads
 You may not post replies
 You may not post attachments
 You may not edit your posts

Forum Rules

Click Here to Expand Forum to Full Width
This a Codeguru.com survey!
