jamboree / bustache

C++20 implementation of {{ mustache }}
82 stars 10 forks source link

Search Bustache Object for data - enhansement #21

Closed carolinebeltran closed 4 years ago

carolinebeltran commented 4 years ago

Jamboree, I thought that the following modification would not be difficult but I cannot figure out how to make the Printer object return values, for example:

std::cout << bustache::visit(Printer{}, result->second) << '\n';

I tried to modify the operator so that a value is returned.

#include <iostream>
#include <string>
#include <bustache/model.hpp>

struct Printer
{
    int operator()(int val) { return val; }
    double operator()(double val) { return val; }
    std::string operator()(std::string const& val) { return val; }

    template<class T>
    void operator()(T const&) { std::cout << "(something else)" << '\n'; }
};

int main()
{
    bustache::object bustObj
    {
        {"1IX99OAVFXOA", 123}
    };

    // find a key in the Bustache container
    auto result = bustObj.find("1IX99OAVFXOA");

    if (result != bustObj.end())
    {
        // display the first value
        std::cout << result->first << '\n'; // 1IX99OAVFXOA

        // display the second value
        // bustache::visit(Printer{}, result->second);
        std::cout << bustache::visit(Printer{}, result->second) << '\n';
    }
}

Of course, I was unable to figure out how to get values returned.

jamboree commented 4 years ago

You can't return different types for a visitor. The return type must be the same, e.g.

struct SizeOf
{
    template<class T>
    std::size_t operator()(T const&) { return sizeof(T); }
};

Then you can do something like:

std::cout << "internal size: " << bustache::visit(SizeOf{}, result->second);

That said, I'm not sure what you're trying to do actually. Bustache is mostly for formatting, it's seldom that you want to introspect the model value.

carolinebeltran commented 4 years ago

Thank you Jamboree. I do use Bustache as designed for formatting. I just have a special case where I would like to look up information stored inside the container.