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

无参数情况下的参数转发

  •  1
  • BCS  · 技术社区  · 14 年前

    我有一个这样的班级:

    template<class T> class A : public T {
    
    // this is done to wrap the base class version of a virtual function
    virtual void F(int i) {  
      if(i < 0) T::F(-i);
      else T::F(i);
    }
    
    //...
    

    它需要能为任何一组参数构造,基类可以用以下方法构造:

    template <typename T1> A(T1 t1) : T(t1) {} 
    template <typename T1, typename T2> A(T1 t1, T2 t2) : T(t1, t2) {} 
    // ho, hum, copy, paste, yuck.
    // ....
    

    除了默认的构造函数外,一切都很好:

    template <> A() : T() {}
    

    不编译

    A() : T() {} 
    

    如果t没有默认构造函数,即使未调用(),也会失败。

    }
    

    有办法吗 A() 没有参数的模板?

    4 回复  |  直到 14 年前
        1
  •  2
  •   UncleBens    14 年前

    如果t没有默认构造函数,则失败 即使没有调用()。

    class X
    {
    public:
        X(int) {}
    };
    
    template <class T>
    class A: public T
    {
    public:
        A(): T() {}
        template <class U>
        A(const U& u): T(u) {}
    };
    
    int main()
    {
        A<X> a(1);
        //A<X> b;
    }
    

    这似乎可以用几个编译器进行编译。除非实际使用,否则未使用的方法不会导致特定模板参数出错,这难道不是类模板的意图吗?

    可能是在某个地方调用了a的默认构造函数?


    标准中有这个例子来说明类模板和成员函数是如何实例化的。注意,类和成员的实例化是分开的:

    -3-[示例:

    template<class T> class Z {
    public:
        void f();
        void g();
    };
    
    void h()
    {
        Z<int> a;               //  instantiation of class  Z<int>  required
        Z<char>* p;             //  instantiation of class  Z<char>  not
                    //  required
        Z<double>* q;           //  instantiation of class  Z<double>
                    //  not required
    
        a.f();                  //  instantiation of  Z<int>::f()  required
        p->g();                 //  instantiation of class  Z<char>  required, and
                    //  instantiation of  Z<char>::g()  required
    }
    

    本例中的任何内容都不要求隐式实例化类Z、Z::G()或Z::F()。]

    据我所见,这意味着不仅类模板中的模板方法被“惰性地”实例化,而且常规成员也是如此。

        2
  •  1
  •   David    14 年前

    如果您可以访问C++0x,以避免所有样板(下)和一般地缩放到任意数量的参数,可能需要查看变量模板。

    template <typename T1> A(T1 t1) : T(t1) {} 
    template <typename T1, typename T2> A(T1 t1, T2 t2) : T(t1, t2) {} 
    ...
    

    http://www2.research.att.com/~bs/C++0xFAQ.html#variadic-templates

        3
  •  0
  •   tenfour    14 年前

    如果 T 没有默认的构造函数,那么您实际上没有任何选项。 A() : T() { } 在这种情况下是一个明显的错误。对你所处的情况有一个更宽泛的看法,也许有更好的/不那么复杂的方法可以完全做到这一点。

        4
  •  0
  •   stefanB    14 年前

    总之,您不能编译 T() 如果 T 没有默认构造函数。