【问题标题】:Retrieving the base type(s) from a template parameter从模板参数中检索基本类型
【发布时间】:2011-11-16 03:45:51
【问题描述】:

是否有可能以某种方式获取某个类的基础,以便可以像这样(伪代码)向上传递模板链

template<typename base>
class first
{
    template_taking_base<base>* member;
}

template<typename derived>
class second: public first< function_giving_me_base_of_derived >
{
    derived* get( string s ) { dynamic_cast<derived>( member->get_base( s ) ); }
}

为了避免

template<typename base, typename derived>
class second: public first<base>
{
  //...
}

为什么需要这样做?

我有两种不同类型的资源,一种在主内存中,另一种在 gpu 内存中,目前看起来像这样:

         basic_resource
         /           \
        /             \
   cpu_resource   gpu_resource
       |               |
   many_derived    many_derived

我也有这些资源的句柄。这个想法是你有

handle<image> someimage("blah.bmp")
image the_image = someimage.get();

get 函数要求缓存获取资源的位置。缓存返回 cpu_resource 或 gpu_resource,而句柄动态将其转换为模板化资源(在上述情况下为图像)。

缓存本身就是一个模板

template<typename resource_base>
class cache
{
public:
//...
   resource_base* get_resource( string name )
private:
//...
}

resource base 应该是 cpu_resource 或 gpu_resource 之一,在缓存模板的各种成员函数中具有适当的特化。

所以句柄,保持一个指向缓存的指针,必须知道它是一个句柄的资源的基本类型。

具体

template<typename resource_type>
class handle
{
  string name;
  cache< /*need the base of resource_type here*/ >* cache

  resource_type* get( void ) { dynamic_cast<resource_type>( cache->get( name ) ); }
}

我试图概括这个问题,以便我可以更快地得到答案,但这没有用,所以也许这会。如果您需要更多细节,请询问。

【问题讨论】:

  • 您能否发布一个小的使用示例,说明如何以及在何处需要这样做?
  • 问题/例子/需要不清楚。

标签: c++ templates typetraits


【解决方案1】:

任何 派生 类都已经属于 base 类型,那么为什么要这样做呢?

如果你必须这样做,你可以这样做

class A
{   
public:
    A()
    {
    }
};

class ADer : public A
{
public:
    typedef A base_t;
};

class B
{
public:
    B()
    {
    }
};

class BDer : public B
{
public:
    typedef B base_t;
};

template <typename T>
void Foo()
{
    typename T::base_t x;
    // Here x will always be base class of T
}


int main()
{
    Foo<BDer>();
    Foo<ADer>();

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多