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)
假设,截至目前这不是一个问题.]
使用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)
| 归档时间: |
|
| 查看次数: |
960 次 |
| 最近记录: |