[英]How to forward std::initializer_list<T>?
I am trying to forward a std::initializer_list
but 我试图转发
std::initializer_list
但是
no known conversion from 'std::initializer_list<A>' to 'std::initializer_list<B>'
Here is the test code 这是测试代码
#include <iostream>
class B {
};
class A: public B {
};
class not_working {
private:
void fun(std::initializer_list<B> p) {
}
public:
template<typename T>
not_working(std::initializer_list<T> args) {
fun(args);
}
};
class working {
private:
void fun(std::initializer_list<B> p) {
}
public:
working(std::initializer_list<B> args) {
fun(args);
}
};
int main(){
working{A{}, A{}};
//not_working{A{}, A{}};
}
How can I forward the std::initializer_list
如何转发
std::initializer_list
without explicit casting not_working{(B)A{}, (B)A{}};
没有明确的铸造
not_working{(B)A{}, (B)A{}};
? ?
I have a proxy-class that forwards the constructor-parameters to a class. 我有一个代理类,它将构造函数参数转发给一个类。 Something like this:
像这样的东西:
template<typename T>
class proxy {
T real;
template<typename S> proxy(std::initializer_list<S> p): real(p) {}
template<typename S...> proxy(S ... p): real(p ...) {}
};
You cant, and the reason is the same as why you also could not cast a std::vector<A>
to a std::vector<B>
. 你不能,原因与为什么你也无法将
std::vector<A>
转换为std::vector<B>
。 Containers of different types are completely unrelated. 不同类型的容器完全不相关。
The only way to "change" the type of a container is to construct a new container of the new type (eg, std::vector<B>(a.begin(), a.end())
-- but beware of slicing!). “更改”容器类型的唯一方法是构造一个新类型的新容器(例如,
std::vector<B>(a.begin(), a.end())
- 但要小心切片!)。
Posting answer from comments of question to increase visibility of the solution: 发布问题评论的答案以提高解决方案的可见性:
Standard solution is to use std::forward. 标准解决方案是使用std :: forward。 This fails forwarding initializer lists.
这无法转发初始化程序列表。
template<typename T>
class proxy {
T real;
public:
template<typename ... S> proxy(S ... p): real{std::forward<S>(args)...} {}
};
Using std::move, also works with std::initializer_list (provided by @dyp) : 使用std :: move,也可以使用std :: initializer_list(由@dyp提供):
template<typename T>
class proxy {
T real;
public:
template<typename ... S> proxy(S ... p): real{std::move(p) ...} {}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.