简体   繁体   English

C ++部分模板专门化和模板参数中的类继承

[英]C++ partial template specialization and class inheritance in template parameter

Although here is several questions with similar topic, I didn't make my code to work. 尽管这里有几个与主题相似的问题,但是我没有使代码正常工作。 I have following classes: 我有以下课程:

template<class T, class DataGetter>
class LogableTemplate
{
  public:
    //logs data got by dataGetter
    static DataGetter dataGetter;
};
template<class T, class DataGetter> 
DataGetter LogableTemplate<T, DataGetter>::dataGetter;

template<class T, class DataGetter>
class Logable : public LogableTemplate<T, DataGetter>
{
};

I use this class like this: 我像这样使用此类:

class ADataGetter;
class A : public Logable<A, ADataGetter> {}
class ADataGetter {  //generic external functor returning some data
  public:
    int operator()(const A&a) { return 3; }
};

But there is a special case, when I have some class converting other class to required type, like: 但是有一种特殊情况,当我有一些将其他类转换为所需类型的类时,例如:

template <class T>
class IntClassMapper {
  public:
    int mapToInt(const T &t);    
};

It is fine, but it doesn't have required operator(). 很好,但是没有必需的operator()。 I made helper class: 我参加了辅助课程:

template<class T, class Mapper>
class IntMapperDataGetter {
  public:
    int operator()(const T &t) {
      return mapper.mapToInt(t);
    }
  static Mapper mapper;
};
template<class T, class Mapper>
Mapper IntMapperDataGetter<T, Mapper>::mapper;

And not I need a partial specialization for case that second template argument of Logable is inherited from IntClassMapper. 对于Logable的第二个模板参数是从IntClassMapper继承的情况,我不需要部分专门化。 I've tried following code (and hundred of similar), but I always get some compile error - usually: 我试过下面的代码(以及数百个类似的代码),但是我总是会遇到一些编译错误-通常:

error: template parameters not deducible in partial specialization

Here's the code: 这是代码:

template<class T, class Mapper>
class Logable<T, typename std::enable_if<std::is_base_of<IntClassMapper<T>, Mapper>::value, IntMapperDataGetter<T, Mapper>>::type> : public LogableTemplate<T, IntMapperDataGetter<T, Mapper>>
{
};

You can check and test the code on https://ideone.com/qz9jIt 您可以在https://ideone.com/qz9jIt上检查和测试代码

Is it possible to do it this way? 有可能这样做吗? Thank you, Martin 谢谢马丁

As far I understand, you want your Logger to have different behaviour, based on properties of the template parameter. 据我了解,您希望Logger基于template参数的属性具有不同的行为。 Something like this can help maybe? 这样的事情可能会有所帮助吗?

template
<
  class T, 
  class DataGetter, 
  bool enable = std::is_base_of<QVariantClassMapper<T>, DataGetter>::value
>
class Logable 
  : public LogableTemplate<T, DataGetter>
{
};

template<
  class T, 
  class Mapper
>
class Logable<T, Mapper, true> 
  : public LogableTemplate<T, QVariantMapperDataGetter<T, Mapper> >
{
};

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

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