问题
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