【发布时间】:2013-08-23 14:36:36
【问题描述】:
// VERSION 1
struct Range { int begin, end; };
inline Range getRange()
{
int newBegin, newEnd;
// do calculations
return {newBegin, newEnd};
}
struct Test
{
std::vector<Range> ranges;
inline void intensive()
{
ranges.push_back(getRange());
// or ranges.emplace_back(getRange());
// (gives same performance results)
}
};
// VERSION 2
struct Range { int begin, end; };
struct Test
{
std::vector<Range> ranges;
inline void intensive()
{
int newBegin, newEnd;
// do calculations
ranges.emplace_back(newBegin, newEnd);
}
};
版本 2 总是比 版本 1 快。
事实上,getRange() 被多个类使用。如果我要应用 version 2,会有很多代码重复。
另外,我不能将ranges 作为对getRange() 的非常量引用传递,因为其他一些类使用std::stack 而不是std::vector。我将不得不创建多个重载并有更多的代码重复。
有没有一种通用的方式/习惯来替换返回值?
【问题讨论】:
-
"版本 2 总是比版本 1 快。" -- 这个断言是基于……什么?
-
@MohammadAliBaydoun:不,句号,回头再想一想。
-
@user1837009 没有。返回一个 initializer_list 在道德上等同于返回一个引用。 (这也无济于事)
-
@Vittorio 好吧,如果你要像这样重载,你真的不需要所有这些东西,你可以只拥有两个重载函数而不需要额外的模板类(我假设
T和TItemArgs在你的真实代码中是已知的并且是固定的,所以你只剩下TArgs)。我想到的是something along those lines 允许支持emplace或emplace_back的any 容器,例如。queue/list/deque如果您将来碰巧需要它们。 -
@VittorioRomeo 我正在尝试将一个示例放在一起,但我遇到了麻烦,因为
emplace和emplace_back已超载,因此它默默地未能通过 SFINAE 测试并且从未检测到该功能。请给我一点时间... ;)
标签: c++ c++11 templates return emplace