我正在尝试用 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/