Templates inferring type T from return type

霸气de小男生 提交于 2021-02-10 05:44:07

问题


I have a template as follows:

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

I would like to be able to do something like

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

Is it possible for C++ templates to infer the return type from when they're called, or should I just pass a dummy argument to the template with the type I want to the vector to have? The latter works but is messier.


回答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



来源:https://stackoverflow.com/questions/53563499/templates-inferring-type-t-from-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!