【发布时间】: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