Question

Under what circumstances do extra grouping parentheses break things in C++ (C++11 specifically)? For reasons that are not relevant here, I ended up at one point with an expression that had an extra, unnecessary set of parens around it, and I discovered that the C++11 typeinfo function is_same was determining it to be a different type than the same code without the parentheses. Here is a boiled-down example of the somewhat baffling behaviour:

#include <iostream>
using namespace std;

int main()
{
  string s = "foo";
  cout << std::is_same<decltype(s), decltype(string("foo"))>::value;
  cout << std::is_same<decltype(s), decltype((s))>::value;
  cout << std::is_same<decltype((s)), decltype(string("foo"))>::value;
  cout << std::is_same<decltype((s)+"x"), decltype(string("foo")+"x")>::value;

  return 0;
}

This code prints "1001", which seems to indicate that the extra parens in the middle two lines cause the expression to be of a different type, but using that parenthesised expression in a larger expression makes it once again the same type. On the other hand, if I use typeid to get a name for the type, typeid(s) and typeid((s)) seem to produce the same thing.

I've now worked around the immediate problem, but I still don't understand why this happens in the first place; searching around for "double parentheses c++" and the like doesn't seem to turn up anything relevant (mostly pages about operator overloading, and compiler extensions that only activate after a specific keyword).

So: what the heck is going on here? Why is the type of s different from the type of (s)?

Was it helpful?

Solution

decltype treats its arguments differently depending on the additional parentheses.

The second pair of parentheses makes it a primary-expression (but not itself an id-expression or class-member-access), so the special rule doesn't apply.

Here is a discussion: Significance of parentheses in decltype((c))?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top