Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ decltype deducing current function returned type

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:

  1. If I change function name I must change

    decltype(test())

    into

    decltype(name())

  2. 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?

like image 510
Luke Givens Avatar asked Jan 28 '14 17:01

Luke Givens


People also ask

What does decltype return?

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.

What is the decltype of a function?

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.

What does decltype auto do?

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.


1 Answers

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.

like image 143
Casey Avatar answered Oct 09 '22 06:10

Casey