Dylan Klomparens
Dylan Klomparens

Reputation: 2932

Using auto and decltype in templated functions

I've been trying to use auto return type templates and am having trouble. I want to create a function that accepts an STL map and returns a reference to an index in the map. What am I missing from this code to make it compile correctly?

(Note: I'm assuming the map can be initialized with an integer assignment of 0. I will likely add a boost concept check later to ensure it's used correctly.)

template <typename MapType>
// The next line causes the error: "expected initializer"
auto FindOrInitialize(GroupNumber_t Group, int SymbolRate, int FecRate, MapType Map) -> MapType::mapped_type&
{
    CollectionKey Key(Group, SymbolRate, FecRate);
    auto It = Map.find(Key);
    if(It == Map.end())
        Map[Key] = 0;
    return Map[Key];
}

An example of code that calls this function would be:

auto Entry = FindOrInitialize(Group, SymbolRate, FecRate, StreamBursts);
Entry++;

Upvotes: 0

Views: 906

Answers (1)

Jaffa
Jaffa

Reputation: 12710

Add typename before MapType in the suffix return type declaration.

If you forget to add the typename you would get such kind of error (here GCC 4.6.0) :

test.cpp:2:28: error: expected type-specifier
test.cpp:2:28: error: expected initializer

That would give you something like :

template <typename MapType>
auto FindOrInitialize() -> MapType::mapped_type&
{
    ...
}

But for what you are trying to do, there's no need for suffix syntax :

template <typename MapType>
typename MapType::mapped_type& FindOrInitialize() 
{
    ...
}

Here if you forget the typename you get an error like :

test.cpp:2:1: error: need ‘typename’ before ‘MapType::mapped_type’ because ‘MapType’ is a dependent scope

Which is much more explicit!

Upvotes: 2

Related Questions