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;
}

Wich 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?

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.


The question is paradox:

In this example

std::vector<int> test(){
    decltype(test()) ret;
    ret.push_back(5);
    ret.push_back(9);
    return ret;
}

the function has to assume the decltype is a container supporting push_back with a value type of int. There is no way to predict it. Just changing the return type (to double) will break it.


How about :

typedef std::vector<int> my_return_type;

my_return_type test(){
    my_return_type ret;
    ret.push_back(5);
    ret.push_back(9);
    return ret;
}

I think you won't have anything better without macros :)


This might look weird but I think it does what you want it to do.

std::vector<int> create() { 
  std::vector<int> x;
  return x; 
}

auto myfunc() -> decltype(create()) {
  auto X = create();
  return X;
}

Pre-C++1y (and post-C++1y, too), you could use a lambda to do the return type deduction for you, as in:

namespace
{
    auto test = []
    {
        std::vector<int> ret;
        ret.push_back(5);
        ret.push_back(9);
        return ret;
    };
}

Need Your Help

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

java junit

Should I initialize class fields at declaration like this?

Android Custom button with imageview and textview inside?

java android

I'm looking to create a custom button. This button ideally would have an image on the left and a textview on the right. How would I accomplish this?