I have generic class in c
template<typename A>
struct series {
A member;
}
template<typename A,typename B,typename C>
series <C> & operator (A first, const B& second) {
return first second;
}
I need to return type that is implicit conversion of type A and type B. Fox example : double a int b → implicit conversion is double how can I do that, because C cannot be determined like this I was trying something with decltype and typedef but it didn't work Thanks in advance
CodePudding user response:
The standard library provides a number of templates for situations like this. For the moment, let's deal with the really simple case:
template <class T, class U>
returnType operator (T t, U u) {
return t u;
}
So what should we use for returnType
? In this case, we can use std::common_type
, which tells us the common type to which both its operand types will be converted when used in an expression together.
template <class T, class U>
typename std::common_type<T, U>::type add(T t, U u) {
return t u;
}
So, if we passed this an int
and a double
, the return type would be double
.
In most cases, the result type is pretty obvious, but in a few cases, the result can be...interesting, to put it mildly. For example, on an implementation that used 16 bits for both short
and int
(like many MS-DOS compilers did), it's entirely possible that unsigned short int
could have a common type of long
.
CodePudding user response:
You can use C 11 trailing return types with decltype
:
template<typename A,typename B>
auto operator (A first, const B& second) -> decltype(first second) {
return first second;
}