Template return type

majidkamali1370 (202)
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)
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
JLBorges (1336)
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)
@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)
You replace the a+b with the expression that determines the return type.
majidkamali1370 (202)
Thanks guys ;)
JLBorges (1336)
> Whould you please explain that code or give me a link for reading?

Alexandrescu on type traits: http://erdani.com/publications/traits.html

std::common_type<>: http://en.cppreference.com/w/cpp/types/common_type
majidkamali1370 (202)
Thanks
Registered users can post here. Sign in or register to post.