我一直在尝试使用自动返回类型模板,但遇到了问题。我想创建一个接受STL映射并返回对映射中索引的引用的函数。为了使代码正确编译,我在这段代码中遗漏了什么?
(注意:我假设map可以用0的整数赋值进行初始化。我可能会在稍后添加一个boost概念检查,以确保它被正确使用。)
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];
}调用此函数的代码示例如下:
auto Entry = FindOrInitialize(Group, SymbolRate, FecRate, StreamBursts);
Entry++;发布于 2011-10-12 03:50:00
在后缀返回类型声明中,在MapType之前添加typename。
如果你忘记添加typename,你会得到这样的错误(这里是GCC 4.6.0):
test.cpp:2:28: error: expected type-specifier
test.cpp:2:28: error: expected initializer这会给你一些类似的东西:
template <typename MapType>
auto FindOrInitialize() -> MapType::mapped_type&
{
...
}但是对于你正在尝试做的事情来说,不需要后缀语法:
template <typename MapType>
typename MapType::mapped_type& FindOrInitialize()
{
...
}在这里,如果你忘记了typename,你会得到一个错误,比如:
test.cpp:2:1: error: need ‘typename’ before ‘MapType::mapped_type’ because ‘MapType’ is a dependent scope这就更明确了!
https://stackoverflow.com/questions/7731648
复制相似问题