简体   繁体   English

用stl容器实现特征

[英]implementation of traits with stl containers

I have a question concerning implementation of traits with stl containers. 我有一个关于使用stl容器实现特征的问题。

I have some code which should work with different objects (with tensors in my case) and I have no direct access to tensor class (for instance when I use external tensor library). 我有一些代码应与不同的对象一起使用(在我的情况下为张量),并且我无法直接访问张量类(例如,当我使用外部张量库时)。 I try to realize all necessary properties of tensors through traits. 我试图通过特征来实现张量的所有必要属性。

For example, I have a template class which should works with tensor: 例如,我有一个应该与张量一起使用的模板类:

template<typename Traits>
class Operator{
  typedef typename Traits::state_t state_t;
  .........
};

It means that for a particular tensor type I should specify its own traits type. 这意味着对于特定的张量类型,我应该指定其自己的特征类型。 For instance for SomeTensor I do: 例如我为SomeTensor做:

class SomeTensorTraits{
  typedef SomeTensor state_t;
  .........
};

When I want to use other tensor type I just write another traits: 当我想使用其他张量类型时,我只写了另一个特征:

class OtherTensorTraits{
  typedef OtherTensor state_t;
  .........
};

Then I use a different tensor types in the same Operator code and it works fine. 然后我在同一Operator代码中使用不同的张量类型,并且工作正常。

Problems start when I want to collect a different tensors to some stl container (std::vector for example). 当我想将不同的张量收集到某个stl容器(例如std :: vector)时,问题就开始了。 I remind you that I don't have an access to tensor classes (so I can not make tensors derived from some base class) and I also don't want to collect TensorTraits in the container. 我提醒您,我没有访问张量类的权限(因此,我无法使某些基类派生的张量),并且我也不想在容器中收集TensorTraits

Thus the question is how to collect different Tensor objects through implementation of tensors in helper traits? 因此,问题是如何通过在辅助特征中实施张量来收集不同的Tensor对象?

Appreciate your help. 感谢您的帮助。

You can use boost::any to encapsulate objects. 您可以使用boost::any封装对象。 Other way (more dirty) is to use a union that covers all cases. 另一种方法(更脏)是使用涵盖所有情况的联合。

Also you can create IOperator class, derive from it and use vector<IOperator&> for storing references. 您也可以创建IOperator类,从中派生并使用vector<IOperator&>来存储引用。

I think you want generic traits with specialization: 我认为您想要具有专业性的通用特征:

template<typename T>
struct TensorTraits;

template<>
struct TensorTraits<SomeTensor>;
{
    using state_t = SomeTensor;
    // ...
};

template<>
struct TensorTraits<OtherTensor>
{
    using state_t = OtherTensor state_t;
};

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

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