繁体   English   中英

智能指针的模板专门化与普通指针完全相同

[英]Template specialization for smart pointer exactly as normal pointer

以下代码演示了此问题:

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>> 没有优雅的方法来为shared_ptr<>调用A<T*>类型

我希望以下方法:

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类型特征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 */ };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM