【问题标题】:What is the template syntax for an arbitrary container of doubles? [duplicate]任意双精度容器的模板语法是什么? [复制]
【发布时间】:2019-04-26 00:45:08
【问题描述】:

我有一个根据策略对值进行舍入的函数

double round(double f, Policy p);

我现在要做的是构建一个只能应用于双精度容器的版本(由于舍入的工作方式,没有任何其他类型的容器)。

template <class Iterable>
Iterable<double> round(
    Iterable<double> y, Policy p){
    for (auto&& e : y){
        e = round(e, p);
    }
    return y;
}

我知道我的模板语法不正确,但应该是什么?

【问题讨论】:

标签: c++ c++11 templates


【解决方案1】:

你需要使用模板-模板参数:

#include <vector>

template <template <typename...> class Container, typename T>
auto round(Container<T> y){
    for (auto&& e : y){
        // ...
    }
    return y;
}

int main()
{
    std::vector<double> vec = {1.1, 2.2};
    std::vector<double> rounded = round(vec);
}

live on coliru

【讨论】:

  • OP 明确要求将使用限制为仅double 的容器。您的代码编译为std::vector&lt;int&gt; 没有问题。
  • 这仍然是一个优雅的解决方案。如果他们坚持,OP 总是可以在 T 上进行 static_assert。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
  • 2013-05-28
  • 2019-05-20
  • 2021-02-03
相关资源
最近更新 更多