如何导出模板函数的输出类型? [英] How can I derive an output type for the template function?
本文介绍了如何导出模板函数的输出类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对基于模板的乘法函数感到困惑,该函数具有两个输入和一个需要派生的类型。我应该如何导出函数的类型?
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;
}
好吧,我知道 auto
或 decltype(auto)
可以很好地完成工作,但是如果可以的话,我想换一种方式,学习是一个原因。例如,对于Eigen,
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;
}
DERIVED_TYPE
应该当然是 Matrix< double,2,4>
。
推荐答案
在这种特定情况下:
DERIVED_TYPE multiply(Matrix<int, 2, 3> t, Matrix<double, 3, 4> u) {
return t * u;
}
您可以使用 std :: common_type
得出的常见类型double
和 int
:
Matrix< std::common_type<int,double> , 2 , 4>
通常:
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>) {
//...
}
这篇关于如何导出模板函数的输出类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文