【问题标题】:comparison function of an associate container data member in class类中关联容器数据成员的比较函数
【发布时间】:2009-05-06 09:17:14
【问题描述】:

我有这样的课:

class MyClass{
public:
    MyClass(int Mode);
private:
    std::map < int, std::string, CompFunc > data;
};

数据成员必须根据Mode参数使用不同的比较函数。

if Mode == 1, then use CompFunc1.
if Mode == 2, then use CompFunc2.
etc.

但是 CompFunc 模板参数是固定在那里的,我怎么能动态地使它呢?

谢谢。

【问题讨论】:

    标签: c++ visual-c++


    【解决方案1】:
    struct Cmp
    {
        explicit Cmp(int mode) : mode_(mode) {}
    
        bool operator()(int lhs, int rhs) const
        {
            switch (mode_)
            {
                case 1: return CompFunc1(lhs, rhs); break;
                case 2: return CompFunc2(lhs, rhs); break;
                // etc.
            }
        }
    
    private:
        int mode_;
    };
    
    class MyClass
    {
    public:
        explicit MyClass(int Mode) : cmp(mode), data(cmp) {}
    private:
        Cmp cmp;
        std::map<int, std::string, Cmp> data;
    };
    

    【讨论】:

      【解决方案2】:

      您可以使用与 map 相同的比较谓词。

      class MyClass
      {
          CompFunc cmp;
          map<int, std::string, CompFunc> data;
      public:
          MyClass(int Mode) : cmp( get_cmpfunc(Mode) ), data(cmp) {...}
          bool operator == (...)
          {
              cmp(...);
          }
      };
      

      【讨论】:

        【解决方案3】:

        编写一个符合正确接口的包装类/函数,但根据模式(或其他变量)分派到正确的函数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-03-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-19
          • 1970-01-01
          相关资源
          最近更新 更多