I'm making a JSON lib dedicated for my own needs, based on ArduinoJSON
v6.
I try to define StaticJsonDocument<_docSize> doc
in a parametric way but I get this error and I cant find the reason for it:
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp: In constructor 'myJSON::myJSON(char*, int, bool)':
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:28: sorry, unimplemented: use of the value of the object being constructed in a constant expression
StaticJsonDocument<_docSize> doc;
^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: error: 'this' is not a constant expression
StaticJsonDocument<_docSize> doc;
^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: note: in template argument for type 'unsigned int'
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:41: error: invalid type in declaration before ';' token
StaticJsonDocument<_docSize> doc;
^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
I paste only relevant part of the code
myJSON.h
:
#ifndef myJSON_h
#define myJSON_h
#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"
class myJSON
{
private:
int _docSize=100;
bool useSerial;
char _filename[30];
public:
myJSON(char *filename, int docsize, bool useserial=false);
bool file_exists();//char *file=_filename);
bool file_remove();
bool format ();
};
#endif
myJSON.cpp
:
#include "Arduino.h"
#include "myJSON.h"
#include "FS.h"
#include <ArduinoJson.h>
myJSON::myJSON(char *filename, int docsize, bool useserial) {
_docSize = docsize;
useSerial = useserial;
StaticJsonDocument<_docSize> doc;
if (useSerial) {
Serial.begin(9600);
}
if (!SPIFFS.begin()) {
if (useSerial) {
Serial.println("Failed to mount file system");
}
}
else{
sprintf(_filename,"%s",filename);
}
}
1 Answer 1
A class that uses <...>
is called a template class. That class uses a form of substitution at compile time to create a concrete class with those values and tokens substituted.
It is then that concrete class that is used to instantiate your object(s).
However, you are trying to use a runtime variable to convert a template class into a concrete class, and that can't be done at compile time - and there is no such thing as a runtime template in C++.
You need to re-think your implementation methodology.
-
thank you for explaining. My intention is to to be able to define size of JSON buffer- is there a way doing so the way I need it ?guyd– guyd2019年04月24日 09:04:02 +00:00Commented Apr 24, 2019 at 9:04
-
1I would suggest create the JSON object outside your class and pass that object to the constructor. Without knowing what ArduinoJSON does with the buffer and how it's instantiated I can't comment.Majenko– Majenko2019年04月24日 09:04:56 +00:00Commented Apr 24, 2019 at 9:04
-
OK- that it was a good enough workaround. TNXguyd– guyd2019年04月24日 09:26:15 +00:00Commented Apr 24, 2019 at 9:26