c++ - 2个操作数的产品类型

标签 c++ c++11

假设我有这种类型:

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++ 类型提升规则。有没有更好、更正确的方法来返回“合理的”基本类型的值?我担心我可能会为 doublefloat 的乘积返回 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/

相关文章:

c++ - istreambuf_iterator 什么时候抛出异常?

python - 为 Web 应用程序实现张量分解的最有效语言

c++ - 没有用于方法调用的可行的 std::weak_ptr 到 std::shared_ptr 的转换

c++ - std::unique_ptr 如何没有大小开销?

c++ - C++ 编译器如何在 std::async 的延迟执行和异步执行之间进行选择?

c++ - Xcode 错误编译 C++ 预期成员名称或声明说明符后的 ';'

c++ - 如何创建代码段大小应为 16 mb(字节代码)大小的 C++ 程序

c++ - 显示名称功能模板名称

c++ - 可以将 std::condition_variable 与 std::lock_guard 一起使用吗?

c++ 重载 operator() 用于在动态二维数组中赋值