[英]partial specialization of template class issue!
以下代码使我感到困惑
//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 *,这意味着我们未实现所需的功能。 请以更易理解的方式解释。
编译器将始终寻找最专业的匹配项(如果存在歧义,将失败)。
由于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*>
这个是。)
编译器实例化vector<char*>
,它与以下模板匹配:
template<class T>
class vector<T*> {
...
};
为了使该模板生成类vector<char*>
,需要使用T=char
实例化它,而这正是编译器所做的。
当编译器看到类型为vector<char*>
,将不会使用T=char*
实例化模板,因为这将导致错误的类型vector<char**>
。 它将使用T=char
代替,这将导致vector<char*>
。 编译器使用模板参数,这些参数将给出正确的结果类型。
template<class t>
//teacher said that this partial specialization will handle all type of pointers
class vector<t*>
{
...
};
vector<char*> v;
您的困惑来自假设<class t>
的<class 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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.