【问题标题】:How to deal with constructor when input-output type is different for templated class当模板类的输入输出类型不同时如何处理构造函数
【发布时间】:2017-12-26 03:51:05
【问题描述】:

我学习 C++ 的时间很短,下面的问题让我很头疼。

我想要做的基本上是在不引入太多开销的情况下包装现有库,以便包装器库可以与现有库一样快地运行。因此,我倾向于不修改现有库中的任何内容。我这样做是为了使界面(语法)与我的旧代码兼容。

说,现有的类叫做BASE,它也是模板类。 有几种方法可以进行包装,例如继承。为了更好地封装,我决定选择将 BASE 作为 Wrapper 类的成员。

        template<class T>    
        class Wrapper{
        public:
                     Wrapper() : base(){};
     /*error line*/  Wrapper( const Wrapper<double>& a, const Wrapper<double>& b ) : base(a.base, b.base){};
                    // constuct Wrapper<complex<double>> vector from two Wrapper<double> vectors using constuctor from existing class BASE
                    // 'a', 'b' are real and imag part respectively.

             private:
                     BASE<T>   base;
            }; 

以下行无法编译,错误消息是'base is declared as private in the context'

      /*error line*/  Wrapper( const Wrapper<double>& a, const Wrapper<double>& b ) : base(a.base, b.base){};

到目前为止我所做的实验:

。改变

      private:
      BASE<T>   base;

      public:
      BASE<T>   base;

代码符合并给出正确答案。但是,正如我上面所说,我想要数据封装,所以这个解决方案是不行的。

。尽管错误消息表明与访问权限有关,但我认为这是由不同的输入输出类型引起的(输入是两个“双”,输出是“复双”类型)。只要输入的类型和 (*this) 的类型一致,以下 dosomething() 函数就可以工作,没有关于“在上下文中将基声明为私有”的错误。

    template<class T>    
    class Wrapper{
    public:
                 Wrapper() : base(){};
 /*error line*/  Wrapper( const Wrapper<double>& a, const Wrapper<double>& b ) : base(a.base, b.base){};

     void dosomething(const Wrapper<T>& a)
     {
      (*this).base = a.base; // ok, compiles good
     }

         private:
                 BASE<T>   base;
        }; 

如何解决?期待任何有用的 cmets。

【问题讨论】:

    标签: c++ constructor wrapper


    【解决方案1】:

    你可以让你的班级friend属于同一班级,但参数不同:

    template<class T>    
    class Wrapper{
        template <typename U> friend class Wrapper;
    public:
        Wrapper() : base(){}
        Wrapper(const Wrapper<double>& a, const Wrapper<double>& b) : base(a.base, b.base){}
    
    private:
        BASE<T> base;
    }; 
    

    【讨论】:

    • 它有效,谢谢。你能详细说明这背后的原理吗?让同班同学成为朋友对我来说不是很容易理解。
    • Wrapper&lt;int&gt;Wrapper&lt;double&gt; 是两种不相关的类型(即使它们来自同一个模板)。
    • 感谢您的专业回答。我正在就我正在从事的同一个项目提出另一个问题。我希望你能花几分钟提供一些帮助。简单来说,如何处理返回变量以便在包装现有类时获得最佳性能。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    相关资源
    最近更新 更多