这个模板部分专门化代码有什么问题?

What is wrong with this template partial specialization code?

本文关键字:什么 问题 代码 专门化 板部      更新时间:2023-10-16

我使用以下代码:

template<typename t>
struct foo
{
    foo(t var)
    {
        std::cout << "Regular Template";
    }
};

template<typename t>
struct foo<t*>
{
    foo(t var)
    {
        std::cout << "partially specialized Template " << t;
    }
};

int main()
{
    int* a = new int(12);
    foo<int*> f(a); //Since its a ptr type it should call specialized template
}

但是我得到错误

Error   1   error C2664: 'foo<t>::foo(int)' : cannot convert parameter 1 from 'int *' to 'int'  

两个模板的构造函数的值都是t,在您的示例中是int,而不是int*。使用

进行编译
template<typename t>
struct foo<t*>
{
    foo(t* var)
    {
        std::cout << "partially specialized Template " << var;
    }
};
如果

符合您的逻辑,则将int传递给构造函数。(生活)