c++ - 是否有 decltype 的快捷方式

标签 c++ c++11 types decltype associated-types

this answer我写了 C++17 代码:

cout << accumulate(cbegin(numbers), cend(numbers), decay_t<decltype(numbers[0])>{});

这收到了一些关于 C++ 类型关联性质的负面评论,我很遗憾地说我同意 :(

decay_t<decltype(numbers[0])>{}是一种非常复杂的方法来获得:

Zero-initialized type of an element of numbers

是否可以保持与 numbers 类型的关联? ' 元素,而不是键入 30 个字符来获取它?

编辑:

我有很多答案都涉及 accumulate 的包装器或者从 numbers[0] 中提取类型.问题是它们要求读者导航到次要位置以阅读不比初始化代码复杂的解决方案 decay_t<decltype(numbers[0])>{} .

我们必须做更多事情的唯一原因:decltype(numbers[0])是因为array subscript operator返回一个引用:

error: invalid cast of an rvalue expression of type 'int' to type 'int&'

有趣的是,关于 decltype 的论据:

If the name of an object is parenthesized, it is treated as an ordinary lvalue expression

然而,decltype((numbers[0]))仍然只是对 numbers 元素的引用.所以最后这些答案可能与我们可以简化这个初始化的结果一样接近:(

最佳答案

虽然我总是选择按照@Barry 编写辅助函数, 如果 numbers 是一个标准容器,它会导出类型 value_type,这样你可以节省一点复杂性:

cout << accumulate(cbegin(numbers), cend(numbers), decltype(numbers)::value_type());

更进一步,我们可以定义这个模板函数:

template<class Container, class ElementType = typename Container::value_type>
constexpr auto element_of(const Container&, ElementType v = 0)
{
    return v;
}

这给了我们这个:

cout << accumulate(cbegin(numbers), cend(numbers), element_of(numbers, 0));

关于c++ - 是否有 decltype 的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36268132/

相关文章:

c++ - 更改模板类的类型

haskell - 依赖类型 'ZipVector' 应用程序

c++ - 创建一个程序来输出 4 个三角平方数

c++ - 向下指针键入与 shared_ptr 一起使用的级别

c++ - 在 C++ 的纯静态公共(public)接口(interface)上删除复制/赋值运算符是否有意义?

C# 字典在另一个字典中使用 TValue

c++ - "specialize"一个基对象变成派生对象?

c++ - 跨多个文件使用 C++ 类的静态变量

c++ - 在安装应用程序期间或启动应用程序时向 Mac 上的防火墙添加异常(exception)

c++ - 文件打开追加效率随文件大小而降低