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

iam*_*ind 3 c++ templates pointers smart-pointers template-specialization

以下代码演示了此问题:

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>
Run Code Online (Sandbox Code Playgroud)

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 */ };
Run Code Online (Sandbox Code Playgroud)

这种方法有什么问题吗?

[以下类型的用法将发生唯一的潜在问题:

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>"
};
Run Code Online (Sandbox Code Playgroud)

假设,截至目前这不是一个问题.]

bdo*_*lan 6

使用boost,您可以使用has_dereference类型特征MPLif_:

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 */ };
Run Code Online (Sandbox Code Playgroud)

  • @iammilind,`if_`根据编译时条件选择两种类型(Aobj和Aptr).我们基本上将`A`作为基于这种任意条件的两种实现之一的别名 - 在这种情况下,`has_dereference` (3认同)
  • 是否有可能使用C++ 11特定的构造而不是boost来实现这一目标? (2认同)