c++ - 如何使用 C++ 中的模板从 json 中填充尽可能通用的 std::vector (11)?

标签 c++ json templates c++11 stdvector

我将数据保存为 json 文件,我想重新加载它。由于将它们作为 json,它们在加载后是字符串(我使用 boost 属性树)。我写了一个函数来重新解释 std::vector。它工作正常,直到我通过调用此函数进行编译。然后编译器不知道如何正确使用这段代码:

template<typename T_vecType>
std::vector<T_vecType> getValues1D(std::string key)
{
    using boost::property_tree::ptree;

    // determine type
    std::string type;
    type = ptLoad.get(key + ".type", "d");

std::vector<std::string> out;

BOOST_FOREACH(ptree::value_type &v,
              ptLoad.get_child(key + ".value" ))
{
    out.push_back(v.second.data());
}

if(type == "f")
    {
        std::vector<T_vecType> resultf;

        for (int i = 0; i < out.size(); ++i) {
            resultf.push_back( std::stof( out[i].c_str() ) );
        }

        return resultf;
    }
else if(type == "i")
    {
        std::vector<T_vecType> resulti;

        for (int i = 0; i < out.size(); ++i) {
            resulti.push_back( std::stoi( out[i].c_str() ) );
        }

        return resulti;
    }

问题是我需要为每种数据类型对字符串进行不同的解释。这就是我以这种丑陋的方式尝试它的原因。也许我这样称呼:

getValuesVector<int>("vecData");

编译器提示他不能将 float 放入 int 中,因为他认为他将执行第一个 if 语句。我也试过这个:

if( typeid(T_vecType) == typeid(float) && type == "f")
...
if( typeid(T_vecType) == typeid(int) && type == "h")

最佳答案

如果不了解全局,很难回答您的问题。您的问题可能出在您的设计上,但我将首先解释为什么您当前的方法不起作用。

这里的问题是您在不知道它应该返回的类型之前尝试使用模板方法。最终发生的是你得到一个返回 vector<int> 的方法。这可能会返回 vector<float>和一个返回 vector<float> 的方法这可能会返回 vector<int> .这根本行不通。

一个简单的解决方案是在调用您的方法之前确定类型,然后调用适当的版本:

template<typename T_vecType>
std::vector<T_vecType> getValues1D(std::string key)
{
    std::vector<std::string> out;

    BOOST_FOREACH(ptree::value_type &v, ptLoad.get_child(key + ".value"))
    {
        out.push_back(v.second.data());
    }

    std::vector<T_vecType> result;

    for (int i = 0; i < out.size(); ++i) 
    {
        result.push_back(std::stof(out[i].c_str()));
    }

    return result;
}

// Then somewhere in code
if (type == "f")
{
    std::vector<float> resultf = getValues1D<float>(key);
}
else if (type == "i")
{
    std::vector<int> resulti = getValues1D<int>(key);
}

这只是展示了如何使用模板,但并不一定能解决您的整体问题。实际的解决方案可能看起来更像是这个问题的答案:C++ class with template member variable

关于c++ - 如何使用 C++ 中的模板从 json 中填充尽可能通用的 std::vector (11)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22122073/

相关文章:

c++ - 如何将成员函数指针传递给模板函数中的重载方法?

c++ - 使用 cv::Mat 类型时如何在图像上覆盖文本

json - MariaDB 动态列和 JSON?

javascript - 在 Javascript 中解析时将 PHP 转换为 JSON 数组

C++ toString 成员函数和 ostream 运算符 << 通过模板集成

c++ - 模板的正确语法

c++ - 在使用 Visual Studio 2005 调试时调用函数?

c# - C++ 模板和 C# 泛型

c++ - 编译器可以/是否简化涉及函数的逻辑表达式?

ruby-on-rails - 应该如何链接 json 响应,以便 ActiveResource 可以从日期生成 DateTime 对象?