C++ decltype deducing current function returned type

Luke Givens picture Luke Givens · Jan 28, 2014 · Viewed 8.8k times · Source

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())

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

Answer

Casey picture Casey · Jan 28, 2014

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.