嵌套的初始化器列表
我正在尝试在C ++中创建类似于Python的动态。 现在,一种可能的实现方法(当然有缺点)
#include <iostream>
#include <variant>
#include <map>
using namespace std;
class dict;
using Atom = variant<bool, int, double, string, dict>;
class dict {
map<string, Atom> data_;
public:
template<typename T>
bool put(const string& k, T&& v) {
data_[k] = std::forward<T&&>(v);
return true;
}
template<typename T>
T& get(const string& k) {
return std::get<T>(data_[k]);
}
template<class T>
bool contains(T&& k) {
return data_.find(std::forward<T&&>(k)) != data_.end();
}
dict(initializer_list<pair<string, Atom>> kvs) {
for (auto kv : kvs) (this->put(kv.first, kv.second));
}
};
现在考虑到最后一个变异初始化器。问题是,它并不像我想要的那样灵活:
int main() {
// This works:
auto u = dict{
{"a", 9},
{"b", 1.2},
{"c", true},
{"d", dict{
{"e", "f"}
}}
};
// This does not:
auto v = dict{
{"a", 9},
{"b", 1.2},
{"c", true},
{"d", {
{"e", "f"}
}}
};
return 0;
}
问题是,一个人如何重写,以便将必要的初始器列表自动施放为pair&lt&lt; string,atom&gt;
?
I am making an attempt in creating dynamic Python-like dicts in C++.
One possible approach to implementation (which has its drawbacks, for sure) is
#include <iostream>
#include <variant>
#include <map>
using namespace std;
class dict;
using Atom = variant<bool, int, double, string, dict>;
class dict {
map<string, Atom> data_;
public:
template<typename T>
bool put(const string& k, T&& v) {
data_[k] = std::forward<T&&>(v);
return true;
}
template<typename T>
T& get(const string& k) {
return std::get<T>(data_[k]);
}
template<class T>
bool contains(T&& k) {
return data_.find(std::forward<T&&>(k)) != data_.end();
}
dict(initializer_list<pair<string, Atom>> kvs) {
for (auto kv : kvs) (this->put(kv.first, kv.second));
}
};
Now consider this last variadic initializer. The thing is, it is not exactly as flexible as I would want it to be:
int main() {
// This works:
auto u = dict{
{"a", 9},
{"b", 1.2},
{"c", true},
{"d", dict{
{"e", "f"}
}}
};
// This does not:
auto v = dict{
{"a", 9},
{"b", 1.2},
{"c", true},
{"d", {
{"e", "f"}
}}
};
return 0;
}
The question is, how does one rewrite this so that the necessary initializer lists would be automatically cast to pair<string, Atom>
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
多亏了 @jarod42,我设法提出了这一点:
Thanks to @Jarod42, I have managed to come up with this: