我正在编写一个json库,它的用法与nlohmann/json相同。但是我很难理解nlohmann的get()函数。所以我自己实现了一个get(),但是我认为我的方法不是很好,您有什么好的解决方案或建议吗?
#include <vector>
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
bool func(bool) { return 1; }
int func(int) { return 2; }
double func(double) { return 3; }
string func(string&) { return string("4"); }
vector<int> func(vector<int>&) { return { 5 }; }
map<int, int> func(map<int, int>&) {
map<int, int>a;
a.emplace(6, 6);
return a;
}
template <typename T>
T get() {
static T t;
return func(t);
}
int main() {
cout << get<bool>();
cout << get<int>();
cout << get<double>();
cout << get<string>();
cout << get<vector<int>>()[0];
cout << get<map<int, int>>()[6];
}发布于 2022-03-30 10:02:53
你的方式可行,但是
void、reference、.)、get<char>与您的类型不明确,get<void(*)()>会调用func(bool),但幸运的是,也会因为返回类型而无法编译)作为替代办法:
- you might used `if constexpr`:模板T get() { if constexpr (std::is_same_v) {返回true;}std::is_same_v) {返回42;}std::is_same_v) {返回4.2;}std::is_same_v) {返回"Hello“;{std::is_same_v) {返回{4,8,15,16,23,42};}std::is_same_v>) {返回{1,2},{3,4}};} static_assert(always_false::value);}}
- or (full) specialization:模板T get();// No impl,专门化模板<> bool (){返回真;} <> int get() {返回42;} template <> double get() {返回4.2;} template <> std::string get() {返回"Hello“;} template <> std::向量get() {返回{4,8,15,16,23,42};} <> std::map get() {返回{1,2},{3,4}};}
模板结构标签{};bool func(标记){返回真;} int func(标记){返回42;} double func(标记){返回4.2;}std::字符串func(tag) {返回字符串(“Hello”);}std::向量func(tag) {返回{4,8,15,16,23,42};} std::map func(tag>) {返回{{1,2},{3,4}};}#如果0 //允许扩展和模板模板UserTemplateType func(tag) {返回{};} #endif模板T get() {返回函数(标签{});}
https://stackoverflow.com/questions/71672091
复制相似问题