c++ - 通过其基础匹配派生类型的模板

标签 c++ templates metaprogramming

我正在尝试编写一个模板来提取 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 未定义。

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

最佳答案

它不起作用,因为您匹配的是 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 继承看起来很难看。

关于c++ - 通过其基础匹配派生类型的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10145420/

相关文章:

c++ - 如何可视化这些没有出现的数字。 (C++)

c++ - va_start() 修改堆栈

c++ - 类未被识别为 friend

python - 在应用程序模板中启用上下文处理器

c++ - 构建模板类型的编译时列表?

c++ - boost 信号 - 作为参数传递的类型

c++ - 编译器错误 - opencv2/highgui.hpp : No such file or directory

c++ - 可变参数模板的声明点

php - 如何使用 WooCommerce 中的可用或自定义数据扩展 "variation.php"模板文件

julia - 制作宏以将函数标记为已弃用