【发布时间】:2022-01-14 15:00:01
【问题描述】:
下面是模板化List 的简化示例,其中两个append_move() 和append_forward() 函数具有相同的目标,获取参数并将它们放入容器List。第一个append_move() 函数采用按值传递的arg1,然后将其移至emplace_back() 函数。第二个append_move()函数使用arg1的自动推演,然后转发给emplace_back()函数。
append_forward() 函数比append_move() 函数有什么优势吗?应该首选哪个函数?
#include <deque>
#include <string>
#include <utility>
template<typename T>
class List
{
public:
void append_move(T arg1, std::string arg2)
{
list.emplace_back(std::move(arg1), std::move(arg2));
}
template<typename X>
void append_forward(X&& arg1, std::string arg2)
{
list.emplace_back(std::forward<X>(arg1), std::move(arg2));
}
private:
std::deque<std::pair<T, std::string>> list;
};
【问题讨论】:
-
考虑当你实例化像
List<int &>这样的东西时会发生什么。你想允许还是禁止? -
append move 会在调用时复制 arg1,append_forward 不会
-
@ChrisDodd Will not work 也不允许引用集合。 (除非你愿意做一些模板专业化并开始使用 std::reference_wrapper)
-
@PepijnKramer:这取决于容器——可以实现它们以直接支持引用。这就是为什么我问你是允许还是禁止这样做。
-
@Kam 如果
T恰好有任何显式的单参数构造函数,那么从语义的角度来看,这两者甚至都不是等价的。
标签: c++ move template-argument-deduction