Robinson
Robinson

Reputation: 10122

Unusual static_cast syntax

I managed to track a bug down to the following expression:

foo(static_cast<T>(a, b)); // Executes specialisation 1

The closing bracket was in the wrong place. The correct statement should have been:

foo(static_cast<T>(a), b); // Executes specialisation 2

I've never seen static_cast used with the form (a,b), or seen it described anywhere. What does it mean? The former statement returned b.

Upvotes: 5

Views: 239

Answers (3)

Xiaotian Pei
Xiaotian Pei

Reputation: 3260

, is comma operator, so a, b is just b

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361605

static_cast is not a function, it's a keyword, so the comma in a, b is not an argument separator; it is the comma operator. It evaluates a but throws away the result. The expression evaluates to b.

Upvotes: 15

Baum mit Augen
Baum mit Augen

Reputation: 50053

This has nothing to do with static_cast, but "makes use" of the comma operator. Its result is its right hand side, so

foo(static_cast<T>(a, b));

is equivalent to

foo(static_cast<T>(b));

unless a has other effects (which would then be executed and have their result discarded). With the right compiler settings, you will be warned about such things: Live

Upvotes: 8

Related Questions