Strange problem with templates

Hello

Today I was faced with a problem that has not yet been overcome. To explain it I wrote a little program which produces compile-time error at line 48, and error is:
error: request for member 'value' in 'a2', which is of non-class type 'A ()(B (*)())'


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>

class B 
    {
    public:
    int
    toInt( )
        {
        return 42;
        }
    };

class A
    {
    public:
    template<typename _T>
    A( _T val )
        {
        myVal = val.toInt();
        };
        
    template<typename _T>
    A( _T* val )
        {
        myVal = val->toInt();
        };
        
    A( int val )
        {
        myVal = val;
        };
        
    int value( ) const
        {
        return myVal;
        }
        
    private:
    int myVal;
    
    };

int main (int argc, char * const argv[]) {    
    A a1( 3 );
    std::cout << a1.value( ) << std::endl;
    
    A a2( B() );
    std::cout << a2.value( ) << std::endl;
        
    A a3( new B() );
    std::cout << a3.value( ) << std::endl;
    
    std::cin.ignore();
    return 0;
}


But everything works as it should if I pass an variable to the constructor

1
2
3
    B bvar;        
    A a2( bvar );
    std::cout << a2.value( ) << std::endl;


I use gcc 4.2.1

Thanks
a2 is a function declaration: http://en.wikipedia.org/wiki/Most_vexing_parse
Since 'A' doesn't have a constructor that takes 'B' the compiler assumes that it is a function that takes 'B' and returns 'A'.
It's not a problem with A constructors, it's an ambiguity within C++ grammar
I don't get why

type identifier(identifier);

is always parsed as a function declaration. The example from Wikipedia involves an extra set of parentheses. Doesn't the parser look for identifiers in a symbol table? The parser has all the elements needed to know that it's an object, not a type. And in C++ an object is never a type. What would be the type of the argument expected by the declared function?
If you pass an object it will be parsed as a declaration (see OP), if you pass a type it will parse it as a function declaration.
My mistake, I misread the OP :/
Topic archived. No new replies allowed.