简体   繁体   中英

What is the cross-platform way to handle compound literals in C++?

What is the way to use compound literals in C++ in a cross-platform way? I know it's an extension and not 'official' C++, but there must be a way, right?

My struct is:

struct v2 {
    int x, y; 
};

I want to:

  1. change all struct values in one go when a struct is already initialised.
  2. create an object inline, so I can pass a struct directly as an argument to a function

This works, but is very cumbersome:

v2 position = {0,1};
DoSomething(position);
DoSomething( v2 {0,1} );

Works in MSVC, but gives a syntax error in Clang: error: expected ')'

DoSomething( (v2) {0,1} );

Works in Clang, but gives a syntax error in MSVC cl.exe: error C4576: a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax

This works in MSVC, but is a syntax error in Clang error: expected expression

DoSomething( {0,1} );

Also I cannot change the value later on:

position = v2 {1,1};

Works in MSVC, but not in Clang: error: expected '(' for function-style cast or type construction

position = (v2) {1,1};

Works in Clang, but not in MSVC: error C4576: a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax

Anyone with the answer?

Regardless if v2 is defined like this (with all public member variables):

struct v2 {
    int x, y; 
};

or like this (with a converting constructor):

class v2 {
public:
    v2(int X, int Y) : x(X), y(Y) {}

private:
     int x, y; 
};

... you can use it like this if you use C++11 or later ( clang++ -std=c++11 ... ):

void DoSomething(const v2& v) {
    //... do something ...
}

int main() {
    DoSomething({0, 1});

    v2 position = {1, 2};
    DoSomething(position);
    
    position = {2, 3};
    DoSomething(position);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM