Freelance Compiler Solution

I have the following code:

enum nums { a }; class cls { public: cls( nums ); }; void function() { cls( a ); } 

When I try to compile it with gcc, I get the following error:

 test.cpp: In function 'void function()': test.cpp:12:10: error: no matching function for call to 'cls::cls()' test.cpp:12:10: note: candidates are: test.cpp:7:3: note: cls::cls(nums) test.cpp:7:3: note: candidate expects 1 argument, 0 provided test.cpp:5:7: note: cls::cls(const cls&) test.cpp:5:7: note: candidate expects 1 argument, 0 provided make: *** [test] Error 1 

If I replaced the function as follows:

 void function() { cls name( a ); } 

then everything works. It also works if I use a constructor with two arguments. This does not work if I add "explicit" to the constructor.

I get that gcc somehow analyzes this as a definition of a variable of type "cls" named "a", but I am not familiar with such syntax for defining variables. In my opinion, this is a statement defining an anonymous temporary variable of type cls, passing the parameter "a".

Compiled with gcc 4.6.3.

Any ideas?

Thanks, Shahar

+4
source share
2 answers

Brackets are optional. Thus, cls (a); matches cls a; , which declares an object a type cls and initializes it by default (which does not work because there is no corresponding constructor).

To simply create a temporary value that expires at the end of an expression, you can say cls { a }; in C ++ 11 or (cls(a)); (or any number of more mysterious constructions, for example void(0), cls(a); ).

See this answer for more ideas.

+8
source

Another example of the most awkward parsing problem. line:

 cls( a ); 

declares a local variable named a type cls , which is (or should be) initialized by calling the default constructor. Which does not exist, where the error message comes from.

If you really want to create a temporary object that will be immediately destroyed, you can eliminate the ambiguity by putting the entire expression in parentheses:

 (cls( a )); 

In parentheses, definition is not possible; expression can.

+10
source

Source: https://habr.com/ru/post/1490898/


All Articles