加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 非静态模板成员:可能吗?

发布时间:2020-12-16 10:41:38 所属栏目:百科 来源:网络整理
导读:是否可以在类中创建非静态模板字段? 如果没有,如何解决? 应根据需要在编译时创建此类字段. 例 我有很多B级,比如B1,B2,B3. (在实际情况中,他们有更有意义的名字.) 我想创建一个具有非静态模板函数的类D,添加 BX(),每次调用它时,对于每个单独的BX,对于D的某
是否可以在类中创建非静态模板字段?
如果没有,如何解决?

应根据需要在编译时创建此类字段.

我有很多B级,比如B1,B2,B3.
(在实际情况中,他们有更有意义的名字.)

我想创建一个具有非静态模板函数的类D,添加< BX>(),每次调用它时,对于每个单独的BX,对于D的某个实例,必须计数.
(在实际情况中,它会使某些事情变得更复杂.)

这是一个工作demo来实现它.
可悲的是,我目前必须在D中逐个硬编码每个BX,一个接一个(B1,B3): –

class B1{};class B2{};class B3{};
class Counter{
    public: int counter=0;
};
template<class BX>class Tag{};
class D{
    Counter countB1;
    Counter countB2;
    Counter countB3;
    public: template<class BX> void add(){  
        add_(Tag<BX>());
    }
    private:
    void add_(Tag<B1>){ countB1.counter++;}
    void add_(Tag<B2>){ countB2.counter++;}
    void add_(Tag<B3>){ countB3.counter++;}
    public: template<class BX> int get(){
        return get_(Tag<BX>());
    }
    private:
    int get_(Tag<B1>){  return countB1.counter;}
    int get_(Tag<B2>){  return countB2.counter;}
    int get_(Tag<B3>){  return countB3.counter;}
};

这是用法.请注意,D的每个实例都有自己的计数器: –

int main() {
    D d1;
    d1.add<B2>();   d1.add<B2>();   d1.add<B3>();
    std::cout<<d1.get<B1>()<<" "<<d1.get<B2>()<<" "<<d1.get<B3>()<<"n";
    //^ print 0 2 1  
    D d2;
    d2.add<B1>();
    std::cout<<d2.get<B1>()<<" "<<d2.get<B2>()<<" "<<d2.get<B3>()<<"n";
    //^ print 1 0 0  (not 1 2 1)
    return 0;
}

我的梦想是: –

class D{
    Counter<BX> countBX; //???
    public: template<class BX> void add(){  
         Counter<BX>::getNonStaticInstance(this).counter++; //???
    }
    public: template<class BX> int get(){
        return Counter<BX>::getNonStaticInstance(this).counter; //???
    }
};

如果countBX是静态的,我知道怎么做,但对于非静态,它似乎是不可能的.

解决方法

使用std :: map std :: unordered_map(来自Yakk的建议;感谢)索引和RTTI?

#include <map>
#include <iostream>
#include <typeindex>

class B1 {};
class B2 {};
class B3 {};

class D
 {
   private:
      std::unordered_map<std::type_index,std::size_t> bxMap;

   public:
      template <typename BX>
      void add ()
       { ++ bxMap[std::type_index(typeid(BX))]; }

      template <typename BX>
      int get ()
       { return bxMap[std::type_index(typeid(BX))]; }
 };

int main ()
 {
   D d1;
   d1.add<B2>();    d1.add<B2>();   d1.add<B3>();
   std::cout<<d1.get<B1>()<<" "<<d1.get<B2>()<<" "<<d1.get<B3>()<<"n";
   //^ print 0 2 1
   D d2;
   d2.add<B1>();
   std::cout<<d2.get<B1>()<<" "<<d2.get<B2>()<<" "<<d2.get<B3>()<<"n";
   //^ print 1 0 0
   return 0;
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读