std::使用写入时复制分支转发
std::forward with copy-on-write branching
我正在尝试做一些事情来达到
template <typename T>
void somemethod (T&& t) {
foo(static_cast<const T&>(t));
bar(std::forward<T>(t));
}
这样
如果
foo()
对t
进行更改,它将在副本上运行。(类似于写入时复制(一旦
foo()
完成t
,t
就会直接转发给bar()
这可能吗?写的是否正确?编译器会理解我想要做什么吗?
我是否需要创建一些帮助程序类来实现这一点?
同样,如果我尝试以下情况怎么办:
template <typename T>
void somemethod (T&& t) {
foo(std::forward<T>(t));
bar(std::forward<T>(t));
}
这样
- 然后将
foo()
使用的相同t
转发给bar()
写入时复制是类的属性,没有好方法可以在somemethod
中发生这种情况。 你可以防止foo
意外修改参数,方法是给它一个const
参数,你正在这样做,但你也把它作为一个右值传递,这是不必要的,而且很奇怪。我从未见过const T&&
的用例. 人们要么使用const T&
,要么使用T&
或T&&
。 在您的情况下,我会推荐const T&
.
template<class T> //I'm assuming you forgot to paste this bit
void somemethod (T&& t) {
foo(static_cast<const T&>(t));
bar(std::forward<T>(t));
}
如果你真的想绝对确定foo
在任何情况下都不能t
,你可以给它一份t
的副本而不是 const 引用,但这对于任何理智的情况来说都是矫枉过正的。
这个问题可能有更好的解决方案,但你可以这样做
template <typename T>
void somemethod (T&& t) {
T tmp_t = foo(std::forward<T>(t));
bar(std::forward<T>(tmp_t));
}
甚至更简单:
template <typename T>
void somemethod (T&& t) {
bar(foo(std::forward<T>(t)));
}
这样foo就有办法报告它是否真的改变了任何东西,但它的签名必须改变:
template <typename T>
T foo(T&& t){
if (want_to_modify){
T result;
// here you insert data that get modified form t
return std::forward<T>(result);
}else{
return std::forward<T>(t);
}
}
}
这样,如果不修改,T
的实例只会通过foo
。
另一种方法是直接在T
中实现写入时复制,但是如果您不需要在使用它T
的任何地方都使用它,这可能是一个更好的解决方案。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 使用strcpy将char数组的元素复制到另一个数组
- 是否可以初始化不可复制类型的成员变量(或基类)
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 复制列表初始化的隐式转换的等级是多少
- IPC使用多个管道和分支进程来运行Python程序
- 当从函数参数中的临时值调用复制构造函数时
- 有可能在Armadillo中复制MATLAB circshift方法吗
- 复制几乎为空的数组的最快方法
- 以下示例中如何避免代码复制?C++/库达
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 如何删除peer if else分支中的冗长句子
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 不能将复制初始化与隐式转换的多个步骤一起使用
- 当有分配器意识的容器被复制/移动时,反弹分配器是否被复制/移走
- 为什么复制而不是移动数据元素?
- std::使用写入时复制分支转发