[英]Overloading factory function for rvalue and lvalue reference - efficient initializing
Consider following piece of code: 考虑以下代码:
struct b{
//slow to copy, fast to move data
};
template<class T>
struct c{
c(T &&, b &&){}
c(T &&, const b &){}
//do I have to provide both?
};
template<class T>
auto
make_c(T &&t, b &&_){
return c<T>(std::forward<T>(t), std::move(_));
}
template<class T>
auto
make_c(T &&t, const b &_){
return c<T>(std::forward<T>(t), _);
}
//do I have to make both make_c overloads?
As the comments say - is it necessary to make both rvalue and lvalue make_ functions/constructors or is there a way to avoid code duplication. 就像评论所说的那样-是否必须同时制作rvalue和lvalue make_函数/构造函数,还是有一种避免代码重复的方法。 I must say I feel somehow uncomfortable with copying most of the function code just removing move function.
我必须说,我对删除大多数功能代码只是删除移动功能感到不舒服。
PS: This is a synthetic example - adding additional template argument(s) is impossible due to msvc compiler issues with operator |
PS:这是一个综合示例-由于msvc编译器与
operator |
有关的问题,因此无法添加其他模板参数operator |
overloading. 超载。
If you want to avoid copying the code, you'll need to use a forward reference . 如果要避免复制代码,则需要使用前向引用 。 These, however, are based on a template argument deduction.
但是,这些基于模板自变量推导。 That is, you could use something like this:
也就是说,您可以使用以下方式:
template<typename T, typename B>
auto
make_c(T&& t, B&& _){
return c<T>(std::forward<T>(t), std::forward<B>(_));
}
While it may work to use manual overloading doing so doesn't quite work when you got multiple arguments requiring different treatment for lvalue and rvalue arguments: the number of overloads needed grows exponentially with the number of such arguments. 尽管使用手动重载可能会起作用,但是当您有多个参数需要对lvalue和rvalue参数进行不同的处理时,这样做并不能完全起作用:所需的重载数量会随此类参数的数量呈指数增长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.