8

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
smallB
  • 16,662
  • 33
  • 107
  • 151
  • 1
    Is `call_mem` a member-function or a free function? If it is a free function, it should probably take `memory_` as parameter. Then you could simply make `call_mem` a function template. If it is a member-function the your class could provide a `typedef` for the type of `memory_`. – Björn Pollex Nov 17 '11 at 09:19
  • @BjörnPollex hi, thanks, the idea with typedef is nice too. +1 – smallB Nov 17 '11 at 10:14

3 Answers3

5

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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

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

auto call_mem() -> decltype(memory_)::value_type
{
    return memory_[0];
}
Jason
  • 31,834
  • 7
  • 59
  • 78
  • 1
    This is only necessary if the return type somehow depends on function arguments; in this case, the return type is dependent on a class member, so I don't think trailing return type is relevant. – ildjarn Nov 17 '11 at 19:32
  • If I remove the trailing return-type, I get an error from GCC saying `error: 'call_mem' function uses 'auto' type specifier without late return type` – Jason Nov 17 '11 at 20:02
  • Bizarre... Can't say I know offhand what the correct behavior is. – ildjarn Nov 17 '11 at 20:23
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.)

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005