Reputation: 782
I am trying to port a program I've written in JavaScript to C++ to make it faster. In that program, I dealt somewhat with JSONs. So, I tried to make a method for converting a vector of strings into JSON:
#include <iostream>
#include <vector>
#include <string>
class std::vector<std::string> {
public: std::string JSON();
};
std::string std::vector<std::string>::JSON() {
std::string ret="[";
if (this->size()==0) {
ret+="]";
return ret;
}
int currentSize=this->size();
for (int i=0; i<currentSize; i++) {
if (i!=currentSize-1)
ret+="\""+this->operator[](i)+"\",";
else
ret+="\""+this->operator[](i)+"\"]";
}
return ret;
}
int main(int argc, char **argv) {
std::vector<std::string> fieldOfStrings({"Hello","world","!"});
std::cout <<fieldOfStrings.JSON() <<std::endl;
return 0;
}
However, it doesn't compile:
/home/teo.samarzija/Documents/AECforWebAssembly/AECforWebAssembly.cpp:5:12: error: too few template-parameter-lists
class std::vector<std::string> {
^
/home/teo.samarzija/Documents/AECforWebAssembly/AECforWebAssembly.cpp:9:13: error: specializing member 'std::vector<std::basic_string<char> >::JSON' requires 'template<>' syntax
std::string std::vector<std::string>::JSON() {
What am I doing wrong? I am fairly new to C++.
Upvotes: 0
Views: 323
Reputation: 64
First, the class std::vector<std::string>
does not make sense. Second, a class is not necessary since you can just define a function similar to your member function that takes in std::vector<std::string>
and return the json string.
For example:
#include <iostream>
#include <vector>
#include <string>
std::string JSON(std::vector<std::string> str) {
std::string ret="[";
if (str.size()==0) {
ret+="]";
return ret;
}
int currentSize=str.size();
for (int i=0; i<currentSize; i++) {
if (i!=currentSize-1)
ret+="\""+str[i]+"\",";
else
ret+="\""+str[i]+"\"]";
}
return ret;
}
int main(int argc, char **argv) {
std::vector<std::string> fieldOfStrings({"Hello","world","!"});
std::cout <<JSON(fieldOfStrings) <<std::endl;
return 0;
}
Upvotes: 1
Reputation: 312
As mentioned above the easiest way is a free function.
std::string JSON(std::vector<std::string>& vec) {
std::string ret="[";
if (vec.size()==0) {
ret+="]";
return ret;
}
int currentSize=vec.size();
for (int i=0; i<currentSize; i++) {
if (i!=currentSize-1)
ret+="\""+vec[i]+"\",";
else
ret+="\""+vec[i]+"\"]";
}
return ret;
}
And call it like
std::cout << JSON(fieldOfStrings) <<std::endl;
Upvotes: 1