Templates inferring type T from return type

  • A+
Category:Languages

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.

 


#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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: