模板成员函数的参数推导不适用于在函数内声明的类?

Ale*_* K. 5 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);
}
Run Code Online (Sandbox Code Playgroud)

编译好了.

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);
}
Run Code Online (Sandbox Code Playgroud)

这失败并出现错误:没有匹配函数来调用'Test :: print(test_it():: A&)'

谁能解释我为什么会这样?谢谢!!!

Geo*_*che 8

在第二个例子中,AB是本地类型,这是不能在C++ 03被用作模板类型参数作为每§14.3.1/ 2:

本地类型,没有链接的类型,未命名的类型或从这些类型中的任何类型复合的类型不应该用作模板类型参数的模板参数.

  • @Alexander K.:注意C++ 0x解除了这个限制.`gcc-4.6.0 -std = c ++ 0x`编译第二个例子就好了. (3认同)