Question

In my class I have a member:

std::vector<std::string> memory_;

Now I'd like to have a fnc returning what's in the memory's first element but I do not want to specify std::string as a return type in case later I decide to use different type for this purpose so I've tried this but it doesn't work:

typename decltype(memory_)::value_type call_mem()
{
    return memory_[0];
}

Any ideas how to specify return type in the most generic way?

Was it helpful?

Solution

As long as you use a standard container, that should work, and I think is okay.

Alternatively, since it is a member of a class, then you can use typedef and expose the value_type as nested type of the class:

class demo
{
   public:
     typedef std::vector<std::string> container_type;
     typedef container_type::value_type value_type;

     value_type call_mem()
     {
         return *std::begin(memory_); //it is more generic!
     }

   private:        
     container_type memory_;
};

Note that *std::begin(memory_) is more generic than both memory_[0] and *memory_.begin() as with it, even arrays would work, but that is less likely to benefit you in real code.

OTHER TIPS

You actually just needed to change your formatting slightly, and use the auto keyword:

auto call_mem() -> decltype(memory_)::value_type
{
    return memory_[0];
}

Actually you could just decltype the whole expression:

decltype(memory_[0]) call_mem()
{
    return memory_[0];
}

But ensure that memory_ is declared before call_mem. (and use std::begin to generalize to other containers as explained by @Nawaz.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top