从返回类型推断类型T的模板

卢西亚诺

我有一个模板,如下所示:

template <class T>
vector<T> read_vector(int day)
{
  vector<T> the_vector;
  {...}
  return the_vector;
}

我希望能够做类似的事情

vector<int> ints = read_vector(3);
vector<double> doubles = read_vector(4);

C ++模板是否可以从调用它们时推断出返回类型,还是我应该将一个虚拟参数传递给具有想要矢量具有的类型的模板?后者有效,但更麻烦。

皮特·斯科特尼克
#include <vector>

struct read_vector
{
    int day;
    explicit read_vector(int day) : day(day) {}

    template <typename T, typename A>  
    operator std::vector<T, A>()
    {
        std::vector<T, A> v;
        //...
        return v;
    }
};

int main()
{
    std::vector<int> ints = read_vector(3);
    std::vector<double> doubles = read_vector(4);
}

演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章