2

我正在尝试编写一个模板来提取 boost::shared_ptr 的基本类型。

我写了这个模板:

template<typename T>
struct ExtractBaseType;

template<typename T>
struct ExtractBaseType<boost::shared_ptr<T> > 
{
    typedef T type;
};

它适用于普通的 shared_ptr。这:

struct A
{
};

ExtractBaseType<boost::shared_ptr<A> >::type  a_thing;
std::cout << typeid(a_thing).name() << std::endl;

打印“1A”。

但是,这不会编译:

struct B : boost::shared_ptr<A>
{
};

ExtractBaseType<B>::type  b_thing;

编译器抱怨 ExtractBaseType 未定义。

为什么这样?这将如何完成?

4

1 回答 1

4

它不起作用,因为您不shared_ptr匹配B。您需要匹配派生的shared_ptr.

template<typename T, class = void>
struct ExtractBaseType;

template<class C>
struct ExtractBaseType<
    C, typename enable_if<
           boost::is_base_of<shared_ptr<typename T::element_type>, T>::value
       >::type
    > 
{
    typedef typename T::element_type type;
};

^ 没有测试,但主要思想就在那里

好问题。也就是说,继承自shared_ptr看起来很丑陋。

于 2012-04-13T17:40:15.447 回答