了解模板部分专业化

Raj*_*war 3 c++ templates

我试图理解模板的部分特化的概念.但是我似乎把它与模板专业化混淆了.我正在考虑以下两个例子

template <typename T> 
struct test
{
   ///Some stuff
};

template <> //Specialization
struct test<int*>
{
   ///Some stuff
};


template<typename t> //Partial specialization
struct test<t*>
{
   ///Some stuff
};
Run Code Online (Sandbox Code Playgroud)

我正在尝试以下方面

test<int*> s;
Run Code Online (Sandbox Code Playgroud)

这会调用专门的模板.我怎样才能调用部分专业课程.有人可以用一个例子解释部分模板和专用模板之间的区别吗?

更新:

在完成答案后,我意识到只有当参数的一个子集需要专门化时,部分模板专业化才能提供帮助.所以我尝试过这样的事情

template <>
struct test<int*>
{
};


//Partial Specialized
template<typename t>
struct test<t, std::string>
{
};

test<int*,std::string> s;  //Error : Too many arguments for class template
Run Code Online (Sandbox Code Playgroud)

这是为什么 ?

qua*_*dev 5

简而言之,在谈论类模板时:

所有3个案例的例子:

#include <iostream>

template<typename T, typename U> //Primary template
struct test
{
   void foo() { std::cout << "\nPrimary"; }
};

template <typename T> //Specialization
struct test<T, int*>
{
   void foo() { std::cout << "\nPartial Specialization"; }
};


template<> //Full specialization
struct test<int*, int*>
{
   void foo() { std::cout << "\nFull Specialization"; }
};

int main()
{
    test<int, double> t1;
    t1.foo();

    test<double, int*> t2;
    t2.foo();

    test<int*, int*> t3;
    t3.foo();
}
Run Code Online (Sandbox Code Playgroud)

输出:

部分专业化

完全专业化

现场演示.


要回答您的更新:

  • 模板特化不能添加参数,它只能专门化现有参数