0

I was expecting an error to be thrown by compiler for initializing a c++ type from a temporary variable of another type.

template <bool>                                                                 
struct A{                                                                       
  A(...);                                                                       
};                                                                              

template <> struct A<false>{                                                    
};                                                                              


class B{                                                                        

};    

class C{                                                                        
  int i;                                                                        
};                                                                          


int main()                                                                      
{                                                                               
  //A a;                                                                        
  B b;  
  C c(B());                                                                      
  A<false> aa(B());                                                             
  cout << "Hello World!!" << endl;                                              
}     

Here I have specialized class A for nontype parameter of type bool and value false, so that it has compiler generated standard constructors only, which should not accept any other type as initializing parameter.

For simplification I have used class C with same result(no error in compilation).

But if I do C c(b); it results in error which I expect: error: no matching function for call to ‘C::C(B&)’

1 Answers1

3

You have encountered the most vexing parse. This

C c(B());                                                                      

is the declaration of a function named c that returns a C object and has one parameter (not given a name, even though with optional parentheses) of type B. You have already a fix, C c(b), but note that initialization with curly braces helps, too:

C c{B{}};   // error                                                                   

Note that it recent version of gcc and clang provide incredibly useful diagnostics, clang++ e.g. without any specific warnings flags remarks that

warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]

C c(B());
 ^~~~~
lubgr
  • 37,368
  • 3
  • 66
  • 117