在模板化函数中使用 auto 和 decltype
我一直在尝试使用自动返回类型模板,但遇到了麻烦。我想创建一个接受 STL 映射并返回对映射中索引的引用的函数。这段代码中缺少什么才能使其正确编译?
(注意:我假设可以使用整数赋值 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++;
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++;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在后缀返回类型声明中的 MapType 之前添加
typename
。如果你忘记添加
typename
你会得到这样的错误(这里是 GCC 4.6.0):这会给你类似的东西:
但是对于你想要做的事情,不需要后缀语法:
如果您忘记了
typename
,您会收到如下错误:这更加明确!
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) :That would give you something like :
But for what you are trying to do, there's no need for suffix syntax :
Here if you forget the
typename
you get an error like :Which is much more explicit!