【问题标题】:Templates inferring type T from return type从返回类型推断类型 T 的模板
【发布时间】:2018-11-30 19:11:23
【问题描述】:

我有一个模板如下:

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++ 模板是否可以从它们被调用时推断出返回类型,或者我应该将一个虚拟参数传递给具有我希望向量具有的类型的模板?后者有效,但更混乱。

【问题讨论】:

  • 不行,这种情况下需要指定类型read_vector&lt;int&gt;。编译器无法推断返回类型。

标签: c++ templates generic-programming


【解决方案1】:
#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);
}

DEMO

【讨论】:

  • 非常聪明,+1。介意为那些可能不知道为什么会这样工作的人稍微解释一下吗?
  • 这个工作需要分配器参数A吗?
  • @GillBates 部分是,否则会默认为std::allocator&lt;T&gt;,并且当目标类型使用不同的分配器时会导致推演失败
  • 这有一个(很容易修复的)缺陷。标准并不能真正保证 std::vector 是两个参数的模板。
  • @SergeyA 即使是这样,如果凡人无法使用,转换运算符为什么要推导出任何附加参数?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 2015-12-14
  • 2013-12-05
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多