android - C++ 方法返回任何数据类型。

标签 android c++ ios json

我正在尝试用 C++ 为 iOS 和 Android 实现一个缓存类。我正在使用 nlohmann JSON ( https://github.com/nlohmann/json) 进行缓存。

我有一个基本的 C++ 类

class Cache
{
private:
 static Cache *instance;
 json j;
public:
 static bool fileExists();
 static Cache* getInstance();

template<typename T> void add(string key, T t) { j[key] = t; }
//template<typename T> T get(string key) { return j[key]; }
void persist();

string toString(); 
};

如您所见,我实现了“添加”方法,该方法接受任何类型作为第二个参数。这是我在 Objective C++ 类(class)中的示例。

    cache = Cache::getInstance();

    cache->add("one", "test");
    cache->add("two", true);
    cache->add("three", 199.9);
//  auto obj = cache->get<void*>("test");
    NSLog(@"%s", cache->toString().c_str()); 

当我将结果打印到控制台时,我得到了正确的数据。现在我的问题是如何实现返回任何类型的“get”方法。我在谷歌上到处查看,找不到解决方案。

如果我想在 Objective C 中实现它,我会使用 (id) 返回任何类型,如下所示

- (id)get:(NSString *)key

我试过了,但出现错误:

auto get(string key) { return j[key]; }

非常感谢您的宝贵时间。

最佳答案

nlohmann JSON 提供了很大的灵 active ,解决你的问题很简单,返回一个json类型的对象。您的函数应如下所示:

json get(string key)
{
    return j[key];
}

或者,您可以尝试:

json get(string key)
{
    try
    {    return object.at(key); }
    catch (std::out_of_range)
    {    return null; } //If the key is not present.
} 

关于android - C++ 方法返回任何数据类型。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32112786/

相关文章:

c++ - Log4cpp 重复记录日志

数组中的 C++ 结构,帮助!

ios - Swift 中 'k' 和 'v' 之间的枚举值有什么区别?

ios - UI 测试 - 访问相机

java - 如何使用 SSLSocket 接受带有 Java 的自签名证书

android - Firestore 如何在回收站 View 中从 firestore 检索数据

Android 应用程序适用于 3g 但不适用于 wi-fi

java - ViewPropertyAnimator - 动画不会第一次出现

c++ - boost::integer_mask gcc 编译器错误

IOS7 Mapkit 标注 : image expected format has changed?