Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument deduction for template member functions does not work for classes declared inside function?

Tags:

c++

templates

struct Test
{
        template <class T>
        void print(T& t)
    {
        t.print();
    }
};

struct A
{
    void print() {printf( "A");}
};

struct B
{
    void print() {printf( "B");}
};

void test_it()
{   
    A a;
    B b;

    Test t;
    t.print(a);
    t.print(b);
}

This compiles fine.

struct Test
{
        template <class T>
        void print(T& t)
    {
        t.print();
    }
};


void test_it()
{   
    struct A
    {
        void print() {printf( "A");}
    };

    struct B
    {
        void print() {printf( "B");}
    };

    A a;
    B b;

    Test t;
    t.print(a);
    t.print(b);
}

This fails with error : no matching function for call to 'Test::print(test_it()::A&)'

Can anyone explain me why this happen ? Thanks!!!

like image 630
Alexander K. Avatar asked Jul 02 '11 07:07

Alexander K.


People also ask

What is template argument deduction?

Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.

Can member functions be declared as template?

Member functions can be function templates in several contexts. All functions of class templates are generic but are not referred to as member templates or member function templates. If these member functions take their own template arguments, they are considered to be member function templates.

How do you declare a template function?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.

What happens when a function is defined as a template?

Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.


1 Answers

In your second example, A and B are local types, which can't be used as template type arguments in C++03 as per §14.3.1/2:

A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

like image 138
Georg Fritzsche Avatar answered Sep 23 '22 23:09

Georg Fritzsche