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

模板化接口-创建泛型模板类以返回任何容器

  •  -1
  • Programmer  · 技术社区  · 7 年前

    template <class T>
    class IValue {
    public:
        virtual I& get() const = 0;
    };
    
    template<typename T>
    class Value : public IValue<T>
    {
    public:
        Value() :m_value()
        {}
        virtual T& get() const override
        {
            return m_value;
        }
        virtual ~Value()
        {}
    private:
        T m_value;
    };
    
    class A
    {
    public:
        A() {}
    };
    
    int main()
    {
        Value<A> a1;
        //a1.get();
    }
    

    但我得到的编译错误如下所述:

     $ c++ -std=c++14 try52.cpp
        try52.cpp:4:17: error: 'I' does not name a type
                 virtual I& get() const = 0;
                         ^
        try52.cpp: In instantiation of 'class Value<A>':
        try52.cpp:32:10:   required from here
        try52.cpp:14:16: error: 'T& Value<T>::get() const [with T = A]' marked override, but does not override
             virtual T& get() const override
                        ^
        try52.cpp: In instantiation of 'T& Value<T>::get() const [with T = A]':
        try52.cpp:34:1:   required from here
        try52.cpp:16:16: error: invalid initialization of reference of type 'A&' from expression of type 'const A'
                 return m_value;
    


    感谢您的评论我得到了这个工作,但它是一个正确的设计:

    template <class T>
    class IValue {
        public:
            virtual const T& get() const = 0;
    };
    
    template<typename T>
    class Value : public IValue<T>
    {
    public:
        Value() :m_value()
        {}
        virtual const T& get() const override
        {
            return m_value; 
        }
        virtual ~Value()
        {}
    private:
        T m_value;
    };
    
    class A
    {
    public:
       A(){}
    };
    
    int main()
    {
       Value<A> a1;
       a1.get();
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Swordfish    7 年前

    在第4行修改了你的排版之后( I 而不是 T )你的编译器会告诉你它不能从 const T T& T& get() const .

    get() const -合格者 this -指针将指向 常数 函数中的对象。您不能使用非- 指非- mutable

    要么不要 常数 T& get() 或者让它返回对 常数T : T const& get() const .