代码之家  ›  专栏  ›  技术社区  ›  Luciano

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

  •  2
  • Luciano  · 技术社区  · 6 年前

    我有一个模板如下:

    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++模板是否可以在调用它们时推断出返回类型,或者我应该将一个哑参数传递给模板,并使其具有向量所要的类型吗?后者有效,但更混乱。

    1 回复  |  直到 6 年前
        1
  •  11
  •   Piotr Skotnicki    6 年前
    #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