假设我有这种类型:
template <typename T, typename U>
using product_type = decltype(::std::declval<T>() * ::std::declval<U>());
我在函数模板中使用
template <typename T, typename U>
product_type<T, U> product(T const a, U const b)
{
return a * b;
}
模板生成的模板函数是否会为 C++ 基本类型返回“合理的”乘积值?我想这将使用 C++ 类型提升规则。有没有更好、更正确的方法来返回“合理的”基本类型的值?我担心我可能会为 double
和 float
的乘积返回 float
。
最佳答案
它返回一个“合理的”类型,正是 a*b
会产生的类型。您的代码也可以写成:
template <typename T, typename U>
auto product(T const a, U const b) -> decltype( a * b )
{
return a * b;
}
或使用 C++14:
template <typename T, typename U>
auto product(T const a, U const b)
{
return a * b;
}
关于c++ - 2个操作数的产品类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19346697/