I would like to automatically deduce the returned type of the function I'm writing.
Example:
std::vector<int> test(){ decltype(this_function) ret; ret.push_back(5); ret.push_back(9); return ret; }
So far the best I've achieved is
std::vector<int> test(){ decltype(test()) ret; ret.push_back(5); ret.push_back(9); return ret; }
Which works but:
If I change function name I must change
decltype(test())
into
decltype(name())
If I change function parameters I must change as well
decltype(test())
into
decltype(test(param1, param2))
Is there a more elegant way of doing the same?
decltype returnsIf what we pass to decltype is the name of a variable (e.g. decltype(x) above) or function or denotes a member of an object ( decltype x.i ), then the result is the type of whatever this refers to. As the example of decltype(y) above shows, this includes reference, const and volatile specifiers.
If the expression parameter is a call to a function or an overloaded operator function, decltype(expression) is the return type of the function. Parentheses around an overloaded operator are ignored. If the expression parameter is an rvalue, decltype(expression) is the type of expression.
decltype(auto) is primarily useful for deducing the return type of forwarding functions and similar wrappers, where you want the type to exactly “track” some expression you're invoking.
Name the return type?
template <typename T=std::vector<int>> T test(){ T ret; ret.push_back(5); ret.push_back(9); return ret; }
Please don't make me constrain this with enable_if
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With