mercredi 22 décembre 2021

"expected primary-expression before ‘{’ token" when calling overloaded "<<" with customized data type

I have a simple class 'A' with the following contents:

class A {
public:
    struct data_t {
        int32_t val;
    
        data_t(int32_t _val) :
            val(_val) {
            ;
        };
    };

    A& operator << (const data_t &data) {
        printf("[%s] %d\n", __func__, data.val);
        return *this;
    };

    void func(const data_t &data) {
        printf("[%s] %d\n", __func__, data.val);
    }
};

I tried the following codes and got:

A a;

a<<{100};          //"expected primary-expression before ‘{’ token" 
a<<A::data_t{100}; //OK.
a.func({100});     //OK.

Why a<<{100}; is NG and a.func({100}); is OK?

I don't want to use the second sentence because it is too long and complicated to read.

Aucun commentaire:

Enregistrer un commentaire