vectorXd from_json()? - eigen

I'm trying to implement json serialization of a class using eigen::VectorXd and nlohmann-json library. It's not a problem to store the class as JSON string. How to parse VectorXd from JSON? Is there an other library more suitable for this task?
#include "json.hpp"
class TransformationStep {
public:
VectorXd support_vector;
int number;
TransformationStep(int number_param, VectorXd support_vectorParam) {
number = number_param;
support_vector = support_vectorParam;
}
~TransformationStep() {
}
//json serialization
void to_json(nlohmann::json &j);
void from_json(const nlohmann::json &j);
};
void TransformationStep::to_json(nlohmann::json &j) {
j["number"] = number;
j["support_vector"] = support_vector;
}
void Ftf::from_json(const nlohmann::json &j)
{
number = (j.at("number").get<int>());
//support_vector = j["support_vector"].get<VectorXd>()); //???
}
------ output calling to_json(nlohmann::json &j) ------
{
"number": 3,
"support_vector": [
-0.00036705693279489064,
0.020505439899631835,
0.3531380358938106,
0.0017673029092790872,
-0.9333248513057808,
0.04670404618976708,
-0.21905858722244081,
-1.011945322347849,
-0.09172040021815037,
0.008526811888809391,
0.05187648010664058
]
}

I came up with
void vector_from_json(VectorXd& vector, const nlohmann::json &j) {
vector.resize(j.size());
size_t element_index=0;
for (const auto& element : j) {
vector(element_index++) = (double) element;
}
}

Related

queue of different class objects

I need to create a queue of different class objects (These classes are not related). I found a solution as follows:
Create a base class and use polymorphism.
Here is how I implemented it,
class Task {
public:
virtual void operator()() {
printf("should not be called\n");
}
};
class TaskRPCB : public Task {
private:
int x;
// other varibles
std::function<void(int)> func;
public:
TaskRPCB(std::function<void(int)>&f , int x) {
this->func = f;
this->x = x;
}
void operator()() {
printf("TaskRPCB function is executing...\n");
func(x);
}
};
class TaskECB : public Task {
private:
// other varibles
std::function<void(void)> func;
public:
TaskECB(std::function<void(void)>&f) : func(f) {}
void operator()() {
printf("TaskECB function is executing...\n");
func();
}
};
void F1() { // dummy function for example
cout <<"no x"<<endl;
}
void F2(int x) { // dummy function for example
cout <<"x : "<<x<<endl;
}
int main() {
queue<unique_ptr<Task>> Q;
function<void()> func1 = F1;
function<void(int)> func2 = F2;
TaskECB task1(func1);
TaskRPCB task2(func2,4);
Q.emplace(new TaskECB(func1));
Q.emplace(new TaskRPCB(func2,4));
(*Q.front())();
Q.pop();
(*Q.front())();
Q.pop();
}
The problem is, I can not push the objects directly as shown above. I have to create an object of an inherited class and pass it to another function to do the push action. It is because ( in my case ) the queue is a part of a thread-safe queue and it has separate Push() method.
template<typename T>
void threadSafeQueue<T>::Push(T newData) { /* TODO: size check before pushing */
std::shared_ptr<T> data(std::make_shared<T>(std::move(newData)));
/* construct the object before lock*/
std::lock_guard<std::mutex> lk(mut);
taskQueue.push(data);
dataCond.notify_one();
}
Earlier I did not have multiple tasks to execute ( or push ) into the queue, therefore
threadSafeQueue<TaskRPCB> workQ declaration worked fine for me.
Creating a base Task class like above is not working because of object slicing
Can you suggest other ways to store objects in the queue ( so that I can still use the lock guarded Push() method )
Thanks !
update :
is the correct way of using variant?
typedef std::variant<TaskECB, TaskRPCB> myType;
int main() {
queue<unique_ptr<myType>> Q;
function<void()> func1 = F1;
function<void(int)> func2 = F2;
TaskECB task1(func1);
TaskRPCB task2(func2,4);
myType x = task1;
Q.push(make_unique<myType>(x));
x = task2;
Q.push(make_unique<myType>(x));
if((*Q.front()).index() == 0) {
auto f1 = get<TaskECB>(*Q.front());
f1();
Q.pop();
}
if((*Q.front()).index() == 1) {
auto f1 = get<TaskRPCB>(*Q.front());
f1();
Q.pop();
}
}
update2:
using myVariantType = std::variant<TaskECB, TaskRPCB>;
struct VisitPackage {
void operator()(TaskECB & task) {
task();
}
void operator()(TaskRPCB& task) {
task();
}
};
int main() {
queue<myVariantType> Q;
function<void()> func1 = F1;
function<void(int)> func2 = F2;
TaskECB task1(func1);
TaskRPCB task2(func2,4);
Q.emplace(task1);
Q.emplace(task2);
std::visit(VisitPackage(), Q.front());
Q.pop();
std::visit(VisitPackage(), Q.front());
Q.pop();
}

How to pass a compile time array with var length to a constructor?

I have the following code:
struct MyArrayEntry
{
int type;
int id;
};
template<size_t arraySize>
struct MyArray
{
template<typename T, typename... Types>
MyArray(T t, Types... ts) : data{ { t, ts... } } {}
int dataSize = arraySize;
MyArrayEntry data[arraySize];
};
void Blah()
{
static MyArray<3> kTest
(
{ 1, 4 },
{ 2, 5 },
{ 3, 6 }
);
}
But this fails to build with:
error C2661: 'MyArray<3>::MyArray': no overloaded function takes 3
arguments
What am I doing wrong here?
With the imformation you provide, I would suggest using a std::initializer_list and an std::copy call:
template<size_t arraySize>
struct MyArray
{
const int dataSize = arraySize; // Could as well make it constant
MyArrayEntry data[arraySize];
MyArray(std::initializer_list<MyArrayEntry> elements)
{
std::copy(begin(elements), end(elements), std::begin(data));
}
};
Create as
MyArray<3> kTest({ { 1, 4 }, { 2, 5 }, { 3, 6 } });
Sure it's an extra pair of curly-brackets {}, but it will make your code simpler.

c++ enable, disable class member functions?

Is it possible to enable, disable class member functions?
Situation:
I have a class with 2 types. Each Type has a own constructor. One Type need a function which must not have the other Type.
Example:
class A {
enum struct TypeEnum : int {
TYPE_1 = 1,
TYPE_2 = 2
};
const TypeEnum type;
int x;
A(void) : type(TypeEnum::TYPE_1) { }
A(int _x) : type(TypeEnum::TYPE_2) {
x = _x;
}
// function only for Type 2
void A::operator += (const int& n) {
x = x + n;
}
};
int main() {
A test1 = new A();
A test2 = new A(1);
test1 += 5; // compiler error should be here
test2 += 5; // OK
return 0;
}
Is where something possible like this:
class A {
enum struct TypeEnum : int {
TYPE_1 = 1,
TYPE_2 = 2
};
const TypeEnum type;
int x;
A(void) : type(TypeEnum::TYPE_1) { }
A(int _x) : type(TypeEnum::TYPE_2) {
x = _x;
}
// Is somethig like this realy impossible
void A::operator += (const int& n) -> enable_if(type == TypeEnum::Type2) { // if not compile error
x = x + n;
}
};
You can use specialization:
enum struct TypeEnum : int {
TYPE_1 = 1,
TYPE_2 = 2
};
template<TypeEnum Type>
class A;
template<>
class A<TypeEnum::TYPE_1>
{
public:
A(void) { }
};
template<>
class A<TypeEnum::TYPE_2>
{
public:
A(int _x) {
x = _x;
}
int x;
void operator += (const int& n) {
x = x + n;
}
};
int main() {
A<TypeEnum::TYPE_1> test1;
A<TypeEnum::TYPE_2> test2{1};
test1 += 5; // compiler error should be here
test2 += 5; // OK
return 0;
}
Maybe following may help:
class A {
public:
explicit A(TypeEnum type) : type(type) {}
virtual ~A() {}
protected:
enum struct TypeEnum : int {
TYPE_1 = 1,
TYPE_2 = 2
};
const TypeEnum type;
};
class B : public A{
public:
B() : A(TYPE_1) {}
};
class C : public A{
public:
explicit C(int x) : A(TYPE_2), x(x) {}
C& operator += (int n) { x = x + n; }
private:
int x;
};
inheritance is here to reflect your case with a common type. it is not required else.
A thing you can do anyway:
B make_A() { return B{}; }
C make_A(int x) { return C{x}; }
int main() {
auto test1 = make_A(); // B
auto test2 = make_A(1); // C
test1 += 5; // compiler error should be here
test2 += 5; // OK
return 0;
}
Strange that you didn't get compilation error here:
// function only for Type 2
void A::operator += (const int& n) {
x = x + n;
}
I thought you wanted something like:
// function only for Type 2
A& operator += (int n) {
x = x + n;
return *this;
}
Answering on your question - C++ doesn't work like this. Nevertheless you can implement something similar with templates but I suggest not to do it unless it's just a test program.

Visual C++ initliazing aggregates inline

In g++ I could do this:
struct s
{
int a, b;
};
void MyFunction(s) { }
int main()
{
MyFunction((s) { 0, 0 });
return 0;
}
In Visual Studio however, it doesn't work. is there any way to make it work or some alternative syntax without making a variable and initializing it (and without adding a constructor to the struct as it will make it non-aggregate and it wouldn't be able to initialize in aggregates)?
My C is a bit rusty, but didn't you have to use struct s unless you typedef it? Something like this:
struct s
{
int a, b;
};
void MyFunction(struct s) { }
int main()
{
MyFunction((struct s) { 0, 0 });
return 0;
}
or
typedef struct s
{
int a, b;
} s_t;
void MyFunction(s_t) { }
int main()
{
MyFunction((s_t) { 0, 0 });
return 0;
}

Is it possible to "embed" a structure of variable type into another structure? (GCC)

Is it possible to embed a structure of varying type inside another structure in C?
Basically I want to do something like this.
struct A { int n; void *config; }
struct AConfig { int a; char *b; }
struct BConfig { int a; float b; }
const struct A table[] = {
{ 103, (void*)(struct AConfig){ 1932, "hello" } },
{ 438, (void*)(struct BConfig){ 14829, 33.4f } }
}
Is this possible in C or do I have to define the structures separately?
No, it doesn't work like that. You need explicit storage for each structure:
struct A { int n; void *config; };
struct AConfig { int a; char *b; };
struct BConfig { int a; float b; };
struct AConfig ac = { 1932, "hello" };
struct BConfig bc = { 14829, 33.4f };
const struct A table[] = {
{ 103, &ac },
{ 438, &bc }
};
Edit:
Another possibility is to utilize a union and C99 (-std=c99) named initializers:
enum config_type { CT_INT, CT_FLOAT, CT_STRING };
union config_value {
int int_value;
float float_value;
const char* string_value;
};
struct config {
enum config_type ctype;
union config_value cvalue;
};
struct config sys_config[] = {
{ CT_INT, { .int_value = 12 }},
{ CT_FLOAT, { .float_value = 3.14f }},
{ CT_STRING, { .string_value = "humppa" }}};
void print_config( const struct config* cfg ) {
switch ( cfg->ctype ) {
case CT_INT:
printf( "%d\n", cfg->cvalue.int_value ); break;
case CT_FLOAT:
printf( "%f\n", cfg->cvalue.float_value ); break;
case CT_STRING:
printf( "%s\n", cfg->cvalue.string_value ); break;
default:
printf( "unknown config type\n" );
}
}
You can use a union:
struct AConfig { int a; char *b; };
struct BConfig { int a; float b; };
struct A {
int n;
union {
struct AConfig a;
struct BConfig b;
};
};
Note that a and b are in the exact same space in memory. So if you are going to use the A.a you should not use A.b and vice versa.
Since this is an anonymous union, you can reference both a and b as if they were direct fields of struct A:
struct A sa;
sa.n = 3;
sa.b.a = 4;
sa.b.b = 3.14;
It would work if BConfig had a float pointer to b.
By the way, maybe you need to refactor your code to fit to C syntax.
#include <stdio.h>
#include <stdlib.h>
typedef struct { int n; void *config; } Config;
typedef struct { int a; char *b; } AConfig;
typedef struct { int a; float *b; } BConfig;
int main(void) {
AConfig A;
BConfig B;
A.a= 103;
A.b= "hello";
B.a= 438;
B.b=(float *) malloc (sizeof(float));
*(B.b)= 33.4f;
const Config table[] = {
{ A.a, (void *) A.b },
{ B.a, (void *) B.b }
};
printf("Hi\n");
return 0;
}
You may prefer a union. My union syntax is a little rusty, but something like this:
union config { char* c; float d; };
struct A {int n; int a; union config b;};
const struct A table[] = {
{103, 1932, { .c = "hello" } },
{14829, 438, { .d = 33.4f } }
};
You need C99 for the designated initalizer (the .c or .d in the table), and obviously some way to tell if you're accessing a char* or a float, but I assume you have that covered somewhere else.

Resources