与许多其他C++ 0x用户一样,我试图为我的项目制作智能指针接口。理想情况下,我喜欢这样的语法,隐藏这两种类型和std::make_shared<T>()
调用。如何声明静态函数和typedefs public,它不能被继承?
Foo::Ptr foo = Foo::shared();
Foo::UPtr unique_foo = Foo::unique();
我想打一个声明结构里面继承:
template <class T>
struct SmartDefs
{
typedef std::shared_ptr<T> Ptr;
typedef std::unique_ptr<T> UPtr;
template <class... P>
static Ptr shared(P&&... p)
{
return std::make_shared<T>(std::forward<P>(p)...);
}
template <class... P>
static UPtr unique(P&&... p)
{
return std::unique_ptr<T>(new T(std::forward<P>(p)...));
}
};
现在,这很好地工作本身,但是当继承到图片我得到的问题,因为typedef和共享/唯一静态方法被定义两次。我设法解决此问题,使用一些丑陋的宏,私有继承,需要更多的打字,但我想避免这种情况:
#include <memory>
#include <iostream>
template <class T>
struct SmartDefs
{
typedef std::shared_ptr<T> Ptr;
typedef std::unique_ptr<T> UPtr;
template <class... P>
static Ptr shared(P&&... p)
{
return std::make_shared<T>(std::forward<P>(p)...);
}
template <class... P>
static UPtr unique(P&&... p)
{
return std::unique_ptr<T>(new T(std::forward<P>(p)...));
}
};
#define DECL_SMART(type) using SmartDefs<type>::Ptr; \
using SmartDefs<type>::UPtr; \
using SmartDefs<type>::shared; \
using SmartDefs<type>::unique
class Foo : private SmartDefs<Foo>
{
public:
DECL_SMART(Foo);
virtual void foo() const { std::cout << "Foo" << std::endl; }
};
class Bar : public Foo, private SmartDefs<Bar>
{
public:
DECL_SMART(Bar);
void foo() const { std::cout << "Bar" << std::endl; }
};
template <class T>
struct Baz : private SmartDefs<Baz<T>>
{
DECL_SMART(Baz<T>);
void foo(const T& in) const { std::cout << in << std::endl; }
};
int main()
{
auto foo = Foo::shared();
auto bar = Bar::shared();
auto baz = Baz<int>::shared();
foo->foo();
bar->foo();
baz->foo(10);
foo = bar;
foo->foo();
}
我测试过这样的事情,但它仍然给了我明确的引用到shared()
:
template <class T>
struct SmartPtr : private SmartDefs<T>
{
using SmartDefs<T>::Ptr;
using SmartDefs<T>::UPtr;
using SmartDefs<T>::shared;
using SmartDefs<T>::unique;
};
class Foo : public SmartPtr<Foo> {};