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;
}
Related
Original Code:
typedef struct {
int x;
int y;
} Point;
int main() {
Point point = {1, 2};
printf("%d %d\n", point.x, point.y);
return 0;
}
Use refactor to extract a method:
typedef struct {
int x;
int y;
} Point;
void PrintPoint(Point *point)
{
printf("%d %d\n", (*point).x, (*point).y);
}
int main() {
Point point = {1, 2};
PrintPoint(&point);
return 0;
}
But I want the generated PrintPoint function is like this:
void PrintPoint(Point *point)
{
printf("%d %d\n", point->x, point->y);
}
Is there a configuration in CLion to change (*pStru). to pStru-> when extracting a method?
Unfortunately there is no way to configure the behaviour. There is a bug in CLion tracker about your case. https://youtrack.jetbrains.com/issue/CPP-2193
Maybe it's time to fix it.
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;
}
}
For example, if I have a bool value v, I want a reference to !v that can change when v changes. An example use will be:
class A {
bool& isOpen;
A(bool& value): isOpen(value) {}
void f() {
if (isOpen) {
doSomething();
}
}
};
class B {
bool& isClosed;
B(bool& value): isClosed(value) {}
void g() {
if (isClosed) {
doSomething();
}
}
};
int main() {
bool isOpen = true;
A a(isOpen);
B b(negattive_reference_of(isOpen));
a.f(); // doSomething()
b.g(); // do nothing
isOpen = false;
a.f(); // do nothing
b.g(); // doSomething()
}
Is there anyway in C++ to acheive a similar effect?
Under the hood reference is equivalent to a constant pointer to some variable (compiler just gives you a syntax sugar of how to work with such pointers so that they are always initialized).
So you wan't to have the same variable and two different pointers to it, one of which will dereference to true and the other to false. That is obviously impossible.
The OOP -way to do it would be to pass not reference to boolean but some interface to your classes and use implementation that uses same boolean variable:
class IIsOpenProvider
{
public:
virtual ~IIsOpenProvider() = 0;
virtual bool GetOpenValue() = 0;
};
class IIsClosedProvider
{
public:
virtual ~IIsClosedProvider() = 0;
virtual bool GetClosedValue() = 0;
};
class ValueProvider : public IIsOpenProvider, public IIsClosedProvider
{
public:
bool GetOpenValue() override { return isOpen; }
bool GetClosedValue() override { return !isOpen; }
private:
bool isOpen;
};
class A {
IIsOpenProvider& isOpen;
A(IIsOpenProvider& value): isOpen(value) {}
void f() {
if (isOpen.GetOpenValue()) {
doSomething();
}
}
};
class B {
IIsClosedProvider& isClosed;
B(IIsClosedProvider& value): isClosed(value) {}
void g() {
if (IIsClosedProvider.GetClosedValue()) {
doSomething();
}
}
};
// usage
ValueProvider val;
A a(val);
B b(val);
I found a problem that I guess is due to a bug in GCC.
Anyway, before opening an issue, I would like to be sure.
Consider the code below:
#include<algorithm>
#include<list>
template<typename U>
struct S {
using FT = void(*)();
struct T { FT func; };
template<typename>
static void f() { }
std::list<T> l{ { &f<int> }, { &f<char> } };
void run() {
l.remove_if([](const T &t) { return t.func == &f<int>; }); // (1)
l.remove_if([](const auto &t) { return t.func == &f<int>; }); // (2)
}
};
int main() {
S<void> s;
s.run();
}
clang v3.9 compiles both (1) and (2) as expected.
GCC v6.2 compiles (1), but it doesn't compile (2).
The returned error is:
error: 'f' was not declared in this scope
Moreover, note that GCC compiles (2) if it is modified as it follows:
l.remove_if([](const auto &t) { return t.func == &S<U>::f<int>; }); // (2)
As far as I know, using an const auto & instead of const T & should not alter the behavior in this case.
Is it a bug of GCC?
Per [expr.prim.lambda]:
8 - [...] [For] purposes of name lookup (3.4) [...] the compound-statement is considered in the context of the lambda-expression. [...]
MCVE:
template<int>
struct S {
template<int> static void f();
S() { void(*g)(char) = [](auto) { f<0>; }; }
};
S<0> s;
Hoisting the compound-statement to the context of the lambda-expression gives a clearly valid program:
template<int>
struct S {
template<int> static void f();
S() { f<0>; }
};
S<0> s;
So yes, this is a bug in 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.