Template return type
majidkamali1370 (202)
Oct 31, 2012 at 12:40pm UTC
Hi.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template <typename T>
class Vector3D
{
public :
T x, y, z;
...
};
template <typename T, typename S>
Vector3D<"What is here?" > Cross(const Vector3D<T>& v1, const Vector3D<S>& v2)
{
Vector3D<"What is here?" > result;
// Calculate cross
return result;
}
S, T are primitive types.
What should I put instead of "What is here?" ?
Thanks
L B (3326)
Oct 31, 2012 at 1:27pm UTC
With C++11, there is a way to do this. I don't have enough information from your example to provide an exact solution, but here is an example similar to your situation:1 2 3 4 5
template <typename T, typename S>
auto Add(T a, S b) -> decltype(a + b) //say that the return type is whatever
{ //is returned by the expression (a + b)
return a + b;
}
See: http://www.cplusplus.com/articles/z3wTURfi/
EDIT: JL Borges' soulution is better ;)
Last edited on Oct 31, 2012 at 4:02pm UTC
JLBorges (1336)
Oct 31, 2012 at 2:05pm UTC
1 2 3 4 5 6 7
#include <type_traits>
template < typename T > struct vector3d { /* ... */ } ;
template < typename A, typename B >
vector3d< typename std::common_type<A,B>::type >
cross( const vector3d<A>&, const vector3d<B>& ) ;
majidkamali1370 (202)
Oct 31, 2012 at 4:54pm UTC
@L B:
What if I need to do a more complex work in function instead of a+b ?
@JLBorges:
Whould you please explain that code or give me a link for reading?
Thank you both.
L B (3326)
Oct 31, 2012 at 6:11pm UTC
You replace the a+b with the expression that determines the return type.