产品类型为2个操作数

use*_*108 1 c++ c++11

说我有这种类型:

template <typename T, typename U>
using product_type = decltype(::std::declval<T>() * ::std::declval<U>());
Run Code Online (Sandbox Code Playgroud)

我在函数模板中使用

template <typename T, typename U>
product_type<T, U> product(T const a, U const b)
{
  return a * b;
}
Run Code Online (Sandbox Code Playgroud)

模板产生的模板函数是否会返回C++基本类型的"合理"产品值?我想这将使用C++类型的促销规则.是否有更好,更正确的方法来返回"合理"基本类型的值?我担心我可能会回复一个float产品,例如a double和a float.

Dan*_*rey 5

它返回一个"合理"的类型,正好a*b会产生什么.您的代码也可以写成:

template <typename T, typename U>
auto product(T const a, U const b) -> decltype( a * b )
{
    return a * b;
}
Run Code Online (Sandbox Code Playgroud)

或者使用C++ 14:

template <typename T, typename U>
auto product(T const a, U const b)
{
    return a * b;
}
Run Code Online (Sandbox Code Playgroud)