问题
I am confused with my template-based multiplication function with two inputs and a type that needs to be derived. How should I derive a type of a function?
template<typename T, typename U>
DERIVED_TYPE multiply(T t, U u) {
return t * u;
}
Well, I know that auto
or decltype(auto)
does the work quite well, but I would like the other way if I can, studying is one reason. For example, with Eigen,
DERIVED_TYPE multiply(Matrix<int, 2, 3> t, Matrix<double, 3, 4> u) {
return t * u;
}
the DERIVED_TYPE
should be Matrix<double, 2, 4>
of course.
回答1:
In this particular case:
DERIVED_TYPE multiply(Matrix<int, 2, 3> t, Matrix<double, 3, 4> u) {
return t * u;
}
you can use std::common_type to derive the common type of double
and int
:
Matrix< std::common_type<int,double> , 2 , 4>
In general:
template <typename T1, typename T2, size_t m,size_t n,size_t p>
Matrix< std::common_type<T1,T2>, m,p> multiply( Matrix<T1,m,n>, Matrix<T2,n,p>) {
//...
}
回答2:
In C++11, you can use the operation itself to define the return type via the decltype specifier in conjunction with the auto specifier
template<typename T, typename U>
auto multiply(T const &t, U const &u) -> decltype(t * u)
{
return t * u;
}
In C++14 you can omit the trailing return type in the function declaration
template<typename T, typename U>
auto multiply(T const &t, U const &u)
{
return t * u;
}
In C++20 you can omit the template
specifier and use the abbreviated function template syntax
auto multiply(auto const &t, auto const &u)
{
return t * u;
}
Btw, I have made the arguments const &
to avoid copies of large types.
来源:https://stackoverflow.com/questions/54635703/how-can-i-derive-an-output-type-for-the-template-function