下面的代码演示了这个问题:
template<typename T>
struct A {
// few members and methods...
};
template<typename T>
struct A<T*> {
// different members and methods
};
A<int> ai; // invokes A<T>
A<int*> ap; // invokes A<T*>
A<shared_ptr<int>> as; // oops ! invokes A<T>
A
专用于指针类型。现在在某些地方,我使用智能指针(比如 shared_ptr
),这会导致问题,如示例所示。
一种方法是复制完整的 struct A<T*>
并重写 struct A<shared_ptr<T>>
.有没有优雅的方式调用A<T*>
输入 shared_ptr<>
还有?
我希望采用以下方法:
template<typename T>
struct A<shared_ptr<T>> : public A<T*> { /* empty */ };
这种做法有什么问题吗?
[唯一的潜在问题将发生在以下类型的使用中:
struct A<T*> {
T* p; // for A<int*> ... "typeof(p) = int*"
};
struct A<share_ptr<T>> : A<T*> {
// oops! the "typeof(p)" is still "int*" and not "shared_ptr<int>"
};
假设,到目前为止这不是问题。]
最佳答案
借助 boost,您可以使用 has_dereference
type trait和 MPL if_
:
template<typename T>
struct Aobj { /* T is not a pointer */ };
template<typename T>
struct Aptr { /* T is a pointer-like type */ };
template<typename T>
struct A : public
boost::if_<boost::has_dereference<T>, Aptr<T>, Aobj<T> >::type
{ /* implementation provided by base */ };
关于c++ - 智能指针的模板特化与普通指针完全一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8223153/