谁能解释一下为什么代码不能编译。
template<class T, class DER>
struct Base {
T a;
Base(const T argB) : a(argB){}
};
template<class T>
struct Derived : Base<T, Derived<T> > {
Derived(const T argD) : Base<T, Derived<T> >(argD){}
};
int main() {
int val = 10;
const int *p = &val;
/* this was in the original question
Derived<int*> d(p); // breaks, but compiles with Derived<const int*> d(p);
*/
Derived d(p); // fails, but Derived<const int*> d(p); compiles
}
错误消息是关于没有从int*
to const int*
。照我看来T
可以替换为int*
在这种情况下,构造函数Derived
接收其参数作为const int*
并调用基数const int*
。那么为什么持续的资格会消失呢?
我显然不明白模板参数推导是如何工作的。我无法找到任何清晰但严格且详尽的描述来说明它在什么情况下是如何工作的const
, *
and &
正在玩。也就是说,什么会a
在这些不同的情况下推断出类型。
Foo(T& a)
Foo(T a)
Foo(T* a)
Foo(const T a)
Foo(const T*a)
Foo(const t&a)
when a
is
因为构造函数Derived
is Derived(const T argD)
,所以在你的情况下是Derived(int * const)
。这不接受const int*
.
A “const(指向 int 的指针)”不是一个“(指向 const int 的指针)”.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)