Search code examples
c++c++11return-typedecltypetemplate-argument-deduction

Getting the right value_type


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?


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.