簡體   English   中英

C ++:從模板類繼承並帶有可能變化的構造函數參數

[英]C++: Inheriting from template class with possible varying constructor arguments

假設我們有以下示例類:

class A { 
  public:
    explicit A(int foo) { } 

    void test() {
      cout << "I'm in A" << endl;
    }   
};

class B { 
  public:
    explicit B(string bar) { } 

    void test() {
      cout << "I'm in B" << endl;
    }   
};

我想定義一個子類,以從可以專門化為A或B之一的模板化類繼承。我面臨的問題是A和B具有不同的構造函數參數,因此證明構造Child的構造函數是有點煩人。 如果我執行以下操作,則一切正常:

template <class ParentClass>
class Child : public ParentClass {
  public:
    Child<B>() : ParentClass("foo") {
    }   
};

int main() {
  Child<B> c;
  c.test();
  return 0;
}

但是,我也想做類似Child<A> c事情。 這可能嗎?

謝謝!

您可以專攻每個班級:

template <class ParentClass>
class Child : public ParentClass {
  public:
    Child();
};

template <>
Child<A>::Child() : A(42) {}

template <>
Child<B>::Child() : B("42") {}

演示版

您可以嘗試使用模板化的構造函數,如下所示:

#include <iostream>

using namespace std;

class A {
public:
    explicit A(int foo) { }

    void test() {
        cout << "I'm in A" << endl;
    }
};

class B {
public:
    explicit B(string bar) { }

    void test() {
        cout << "I'm in B" << endl;
    }
};

template <class Parent>
class Child
: public Parent {

public:
    template <class... Args>
    Child(Args... args)
    : Parent(args...) {

    }
};

int main() {
    Child<A> a_child(42);
    Child<B> b_child("42");
    a_child.test();
    b_child.test();
}

如果要讓用戶確定參數,則可以使用委托的構造函數:

template <class ParentClass>
class Child : public ParentClass {
public:
    using ParentClass::ParentClass;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM