【发布时间】:2019-12-19 05:20:27
【问题描述】:
如何获得将两种不同类型相乘的结果类型,即
template< typename TA, typename TB>
struct multiplier
{
using result_type = // something here finds result of TA * TB
result_type operator()( TA a, TB b ) const
{
return a * b;
}
};
我知道在 C++ 中,将两个不同类型的数值相乘是完全有效的,这将给出编译器已知类型的值。 IE。将 double 和 int 相乘将得到 double 类型的答案。
因此,在编译时类型已知的模板类中,应该可以确定将要创建的类型。实际上,可以创建一个 lambda 来返回该值的结果,即
auto foo = [](int a, float b){ return a * b;}
auto c = foo( 13, 42.0 );
这将导致c 成为float。
请注意,我只能使用c++11 或以下的功能。
【问题讨论】:
标签: c++11 c++ class c++11 templates return-type