引用折叠和元组
reference collapsing and and tuples
我正在尝试将参数包转换为引用,因为我的函数的某些参数可能是 r-/l- 值的混合。 有问题的函数:
//must return tuple
template <typename ...U>
std::tuple<U...> input(const char* format, U ...args) {
std::tuple<U...> t = std::tuple<U...> (args...);
//other code....
}
有一些我无法触及的测试代码... 这将调用我的函数:
template <typename... U>
std::tuple<U...> test_input(const char* fmt, U &&...inp) {
input(fmt, std::forward<U>(params)...);
//other stuff...
}
和 2 个测试对象(也是不可触碰的),它们删除了复制/移动构造函数A()
和B()
。 如:
A(const A &) = delete; //same for B
A &operator=(const A &) = delete; //same for B
如果我按原样调用该函数,我将收到"已删除的复制构造函数"或"已删除的构造函数"错误。例如:
test_input("blah blah", 1, i, "a", std::string("a"), A(123) B("string"));
问题是它可以是 r-/l 值的任何组合,我不知道如何将它们转换为所有引用
我知道我需要参考参数。我尝试使用std::forward
、std::forward_as_tuple
、std::make_tuple
,以及将第二个参数更改为input
以U & ...args
和U &&...args
我也明白我需要使用引用折叠:
- A& & 成为 A&
- A& && 成为 A&
- A&& 成为 A&
- A& & && 成为 A&&
我尝试使用第一和第三条规则将任何内容转换为一种A&
,但我仍然收到错误,例如:call to deleted constructor of 'B'
和expects an l-value for 2nd argument
如果我的问题不清楚 - 如何将args
,input
的第二个参数转换为引用元组?
我想你想做这样的事情:
#include <tuple>
#include <string>
//must return tuple
template <typename ...U>
std::tuple<U&&...> input(const char*, U&&...args) {
return std::tuple<U&&...>(std::forward<U>(args)...);
//other code....
}
template <typename... U>
std::tuple<U&&...> test_input(const char* fmt, U &&...inp) {
return input(fmt, std::forward<U>(inp)...);
//other stuff...
}
struct A {
A(int) { }
A(const A &) = delete; //same for B
A &operator=(const A &) = delete; //same for B
};
struct B {
B(const char *) { }
B(const B &) = delete; //same for B
B &operator=(const B &) = delete; //same for B
};
int main() {
int i = 1;
test_input("blah blah", 1, i, "a", std::string("a"), A(123), B("string"));
}
[现场演示]
相关文章:
- C++:TypeDef使用元组
- Pybind11:将元组列表从Python传递到C++
- 重载元组索引运算符-C++
- 在C++中,如何通过几种类型从元组中选择多个元素
- 将fold表达式与std::一起用于两个元组
- std::ranges::elements_view,用于自定义类似元组的数据
- 将元组的向量转换/构造为堆
- 专用于 std 元组的模板,而无需用户执行remove_cvref
- 将元组的向量构造成堆
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 将元组类型扩展为可变参数模板?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 类内部和外部静态 constexpr 元组之间的差异
- 可变参数模板与使用元组在参数中添加不同的数据对
- 访问和打印元组中的数据,并使用 C++14 使用模板函数显示数据
- boost::包含提升单元的元组的哈希值
- 我正在寻找一种优雅的方式来从元组向量创建tuple_element向量
- 如何在可变参数模板函数中遍历可变参数元组?
- 如何使用 SML 随机生成八进制元组
- 引用折叠和元组