Re: Object instantiation gets parsed as func.def.?

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Doug Harrison [MVP] (dsh_at_mvps.org)
Date: 12/06/04


Date: Mon, 06 Dec 2004 16:05:07 -0600

Agoston Bejo wrote:

>Hi! This is the smallest example I was able to create to demonstratet the
>problem. It seems that a certain kind of object instantiation gets parsed as
>a function definition (or whatever) by the compiler. I don't know if it
>comes from some (maybe not-so-)dark corner of the C++ standard, or VC7.1 has
>got a bug.

The "dark corner" theory is correct.

>Thx,
>Agoston
>
>//-----------------------------------
>template<typename T>
>struct A {
> A(T t):t(t) {}
> T t;
>};
>
>template<typename T> void f()
>{
> cout << T() << endl;
> A<T> a1((T()));
> A<T> a2(T()); // function definition?
> cout << a1.t << endl;
> cout << a2.t << endl; // compile error! (*)
>}
>
>int _tmain(int argc, _TCHAR* argv[])
>{
> f<int>();
> return 0;
>}
>
>// (*) error message:
>// error C2228: left of '.t' must have class/struct/union type
>// type is 'overloaded-function'
>// see reference to function template instantiation
>// 'void f<int>(void)' being compiled
>
>//--------------------------------------------

VC is correct. This is what Scott Meyers described as a "vexing parse" in
"Effective STL". To simplify:

 int f(int());

This declares a function f that has one parameter of the type:

 int (*)();

That is, the parameter is unnamed and has type "pointer to a function that
has no parameters and returns int".

You've already discovered one way to get the effect you're after, namely
parenthesizing the ctor argument.

-- 
Doug Harrison
Microsoft MVP - Visual C++


Relevant Pages

  • Re: Object instantiation gets parsed as func.def.?
    ... >a function definition by the compiler. ... "Effective STL". ... has no parameters and returns int". ...
    (microsoft.public.vc.language)
  • Re: Function with unspecified number of arguments
    ... int main ...     return 0; ... you just don't tell the compiler how many. ... you wrote a function definition: ...
    (comp.lang.c)
  • Re: Confusion in ANSI Cs function concepts
    ... A function definition also serves as a declaration, ... and to return an int. ... call does not say anything about the return type then the compiler ...
    (comp.lang.c)
  • Re: It Pays to Enrich Your C Skills
    ... Check if you can score a perfect 10 (without using a compiler). ... int main{ ... struct bitfield { ... out if it is a negative integer constant or a constant expression ...
    (comp.lang.c.moderated)
  • OT: Re: Perl Peeves
    ... I see the result of a test being used as an int. ... the compiler just assumed you knew what you were doing ... introduced to the language later, so void * was unheard of in most code. ... This didn't mean bool was special, declaring it just signaled to the ...
    (comp.lang.perl.misc)