gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:30:02 24 4
gpt4 key购买 nike

下面的代码演示了这个问题:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com