以下代码让我感到困惑
//partial specialization of vector
template<class t>
class vector
{....
};
template<class t>
//teacher said that this partial specialization will handle all type of pointers
class vector<t*>
...
};
这让我很困惑,假设t是char *,因为编译器将首先查找完整的特化,因为这里没有完全的特化,将考虑部分特化。现在它将成为部分特化的char **,因为t是char *,那么这意味着我们没有实现我们想要的功能。请以更易理解的方式解释。
答案 0 :(得分:2)
编译器将始终查找最专业的 匹配(如果存在歧义,则会失败)。
由于char**
匹配两种模式:
char** = T* (with T = char*)
char** = T (with T = char**)
前者更专业,将被选中。 (因为char**
实际上是指向某个东西的指针,我认为“我们没有实现我们想要的功能”是错误的。)
一旦选择了专业化,所有其他候选者将被抛弃(在匹配阶段不会发生递归替换)。例如,
template<class T> struct A {
typedef T type;
static const int value = 0;
};
template<class T> struct A<T*> {
typedef T type;
static const int value = 12;
};
template<class T> struct A<T********> {
typedef T type;
static const int value = 1024;
};
...
A<char**>::type x; // <-- Line X
std::cout << A<char**>::value << std::endl; // <-- Line Y
在第X行和第Y行,模板A
将被实例化。您将第一个模板参数设为char**
。 A
要求使用T********
或T*
或T
的模式。第二个是最佳匹配,因此将选择template<class T> struct A<T*>
。另外两个将会中风。
# FAIL. Not specialized enough. Remove this from consideration.
// template<class T> struct A {
// typedef T type;
// static const int value = 0;
// };
# WIN. Use with T = char*.
template<class T> struct A<T*> {
typedef T type;
static const int value = 12;
};
# FAIL. Does not match char**.
// template<class T> struct A<T********> {
// typedef T type;
// static const int value = 1024;
// };
执行替换后,它变为
struct A<char**> {
typedef char* type;
static const int value = 12;
};
并且X行和Y行将成为
/*A<char**>::type*/ char* x; // <-- Line X
std::cout << /*A<char**>::value*/ 12 << std::endl; // <-- Line Y
(注意:
template<class T> class Vector
不是部分专业化,
template<class T> class Vector<T*>
这个是。)
答案 1 :(得分:2)
当编译器实例化vector<char*>
时,它匹配以下模板:
template<class T>
class vector<T*> {
...
};
要使此模板生成类vector<char*>
,需要使用T=char
进行实例化,这正是编译器所做的。
当编译器看到类型vector<char*>
时,它不会使用T=char*
来实例化模板,因为这会导致错误的类型vector<char**>
。它将使用T=char
代替vector<char*>
。编译器使用模板参数来提供正确的结果类型。
答案 2 :(得分:1)
template<class t>
//teacher said that this partial specialization will handle all type of pointers
class vector<t*>
{
...
};
vector<char*> v;
您的困惑来自假设<class t>
中的t命名您在实例化时给出的完整参数。相反,参数与<t*>
匹配,因此与t = char
匹配。
例如,想象以下专业化:
template <class T> struct Foo {};
template <class T> struct Foo<vector<T> > {}; //specialization for your vector
Foo<vector<int> > f;
再次选择专门化,其中vector<int>
与vector<T>
和T = int
匹配。