代码之家  ›  专栏  ›  技术社区  ›  Jamie

如何在类模板中实现赋值运算符`

  •  1
  • Jamie  · 技术社区  · 6 年前

    我以为我的问题得到了答案 this

    #include <string>
    
    template<class C>
    class tKeySet {
      protected:
        bool set;
        static const std::string key;
    };
    
    template<class C, typename T>
    class tKeySetType : private tKeySet<C> {
      protected:
        T m_val;
    };
    
    template<class C>
    class tKeySetString: private tKeySetType<C, std::string> {
      public:
        tKeySetString<C>& operator=(const std::string &str) {
            this->set = true;
            this->m_val = str;
            return *this;
        }
    };
    
    class foo : private tKeySetString<foo> { };
    template<> const std::string tKeySet<foo>::key = "foo key";
    
    int main(void) {
        foo f;
    
        f = std::string("foo");
    
        return 0;
    }
    

    如何使赋值运算符处于 tKeySetString<C> std::string ?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Vittorio Romeo    6 年前

    foo 继承自 tKeySetString<foo> ,也就是说 operator= 不会成为其公共界面的一部分。

    public:
        using tKeySetString::operator=;