Skip to content

Problem with StaticJsonDocument.as<JsonVariant>() when forwarding a template argument as capacity #977

Closed
@nobodyinperson

Description

@nobodyinperson

Hi Benoît,

I am writing a Json-RPC library based on ArduinoJson and cannot figure out a compilation error I keep getting.

My goal is to have a classmethod as template that takes one argument, namely the capacity of a StaticJsonDocument in the method. When I hard-code the capacity (bad design), everything works. If I use the template argument as capacity, I get error: expected primary expression... at a strange place: when I ise doc.as<JsonVariant>(). (The library uses JsonVariants due to its flexibility).

Wandox Minimal Example

https://wandbox.org/permlink/S4u8O3SSMSbzmJZK

#include <iostream>
#include "ArduinoJson.h"

class MyClass { 
public:
    template<size_t N>
    void method(void) {
        // StaticJsonDocument<100> doc; // hard-coded capacity works
        StaticJsonDocument<N> doc; // <<-- forwareded template argument raises ”error: expeted primary-expression ...”
        JsonVariant var = doc.as<JsonVariant>();
        var["key"] = "value";
        serializeJson(var, std::cout);
    }
};

int main() {
    MyClass myObject;
    myObject.method<100>();
}

Output:

prog.cc: In member function 'void MyClass::method()':
prog.cc:10:45: error: expected primary-expression before '>' token
         JsonVariant var = doc.as<JsonVariant>();
                                             ^
prog.cc:10:47: error: expected primary-expression before ')' token
         JsonVariant var = doc.as<JsonVariant>();
                                               ^

Source code line in library

I neither understand this error nor do I know how to look for solutions :-S I know I could use a DynamicJsonDocument but following the advice in your book I try to avoid the heap as much as possible :-)

Any help would be much appreciated.

Yann

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions