c++ - 智能指针的模板特化与普通指针完全一样

标签 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>

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 traitMPL 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/

相关文章:

c++ - 为具有不同模板参数的模板部分特化模板类

c++ - '仅将成员函数添加到类的专用模板

c - 在 C 中破坏结构的最佳方法是什么

c++ - 仅将继承用于 C++ 中的多态性

C++ .lib 文件到 mex

javascript - Mustache.js 未正确呈现

c - 程序先绕过fgets

c++ - 如何将nana编译成静态库

c++ - 模板:使用前向声明来减少编译时间?

c - 数组和指针的算术