简体   繁体   English

从模板化类定义非模板化类

[英]defining a non-templated class from a templated class

Let's say i've got a templated class called model. 假设我有一个称为模型的模板化类。 now let's declare a class within this class called texture, that requires no template arguments. 现在让我们在该类中声明一个名为Texture的类,该类不需要模板参数。 How do i go about defining it so that no matter the template argument given to the Model class, the texture object is the same. 我该如何定义它,以便无论给Model类提供的模板参数如何,纹理对象都是相同的。 This is what it looks like. 这就是它的样子。

template<class T>
class Model
{
    class Texture;
};

class Model::Texture //error because model requires a template argument.
{


};

so is there anything i can do here? 所以我能在这里做什么?

You should have to write that this way: 您应该这样写:

template<typename T>
class Model<T>::Texture 
{
  //you should be able to use T here, even though Texture is not a template!

   T m_data;   //T here
   Texture(T data); //T here also, as the constructor parameter!

};

As Model is a class template, so here T applies to Model only. 由于Model是类模板,因此T仅适用于Model Texture is still a non-template. Texture仍然不是模板。

Online demo 在线演示

namespace detail {
class Texture
{

};
}

template<class T>
class Model
{
    typedef detail::Texture Texture;
};

The detail namespace would discourage users of your API from accessing that class directly. detail名称空间会阻止您的API用户直接访问该类。 If you don't export any API, you don't have to worry about this. 如果您不导出任何API,则不必为此担心。 The typedef allows access to the non-templated class through a name qualified with the templated one. typedef允许通过限定了模板化名称的名称访问非模板化类。

You could also use a common non-templated ancestor for this: 您也可以为此使用通用的非模板祖先:

class ModelBase
{
    class Texture;
};


template<class T>
class Model : public ModelBase
{

};

class ModelBase::Texture
{

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM