4

次の C++11 コードの問題点:

struct S
{
    int a;
    float b;
};

struct T
{
    T(S s) {}
};

int main()
{
    T t(S{1, 0.1});  // ERROR HERE
}

gcc は指定された行でエラーを返します (gcc 4.5 と gcc 4.6 の実験的ビルドの両方を試しました)

これは有効な C++11 ではありませんか、それとも gcc の実装が不完全ですか?

編集: コンパイラ エラーは次のとおりです。

test.cpp: In function int main():
test.cpp:14:10: error: expected ) before { token
test.cpp:14:10: error: a function-definition is not allowed here before { token
test.cpp:14:18: error: expected primary-expression before ) token
test.cpp:14:18: error: expected ; before ) token
4

2 に答える 2

3

提案N2640によると、コードは機能するはずです。一時的な S オブジェクトを作成する必要があります。g++ は明らかに、このステートメントを (S を期待する関数 t の) 宣言として解析しようとするため、バグのように見えます。

于 2011-01-03T03:22:06.930 に答える
0

括弧なしでコンストラクターを呼び出すのは間違っているようですが、これはうまくいくようです:

struct S
{
    int a;
    float b;
};

struct T
{
    T(S s) {}
};

int main()
{
    T t(S({1, 0.1}));  // NO ERROR HERE, due to nice constructor parentheses
    T a({1,0.1}); // note that this works, as per link of Martin.
}

:sあなたの例が機能しないことは(少なくとも私には)論理的に思えます。S を a に置き換えてもvector<int>、同じ結果が得られます。

vector<int> v{0,1,3}; // works
T t(vector<int>{0,1,2}); // does not, but
T t(vector<int>({0,1,2})); // does
于 2011-01-03T09:56:52.720 に答える