2016-10-08 177 views
11

如何在一般情況下在以下代碼中實現抽象基類。代碼從我正在處理的庫中簡化。所以int和double的顯式實現不是一個選項。在抽象類中使用抽象類時如何實現抽象方法

template <typename T> 
struct Foo 
{ 
    virtual void send(T t) = 0; 
}; 

template <typename...T> 
struct Bar : Foo<T>... 
{ 
    void send(T t) override { // does not compile because 
          // abstract method not implemented 
    } 
}; 

int main() { 
    // example usage 
    Bar<int, double> b; 

    b.send(1); 
    b.send(2.3); 
} 

非常感謝提前。

編輯:增加了虛擬抽象方法。

回答

6

下面的例子呢?首先,我認爲你需要在Foo(如果你想要它是純虛擬的)中定義send()方法virtual

接下來,你可以聲明一箇中間模板類(Foo2),其中實現overridesend()

最後,您可以使用模板send()方法Bar選擇正確的虛擬send()方法。

#include <iostream> 

template <typename T> 
struct Foo 
{ virtual void send(T t) = 0; }; 

template <typename T> 
struct Foo2 : Foo<T> 
{ 
    void send(T) override 
    { std::cout << "sizeof[" << sizeof(T) << "] " << std::endl; } 
}; 

template <typename...T> 
struct Bar : Foo2<T>... 
{ 
    template <typename U> 
    void send (U u) 
    { Foo2<U>::send(u); } 
}; 

int main() 
{ 
    Bar<int, double> b; 

    b.send(1); // print sizeof[4] 
    b.send(2.3); // print sizeof[8] 
} 
+0

嘿,你能告訴我有什麼區別之間:'foo2的 ...'和'foo2的'(括號內點外支架對) – Brandon

+0

@Brandon - 是完全不同的事情;如果你寫'Foo2 ',你用'sizeof ...(T)'模板參數聲明一個基類,'Foo2 ';如果你寫'Foo2 ...',你聲明'sizeof ...(T)'基類,'Foo2 ,Foo2 ,Foo2 /* etc * /',每個都有一個模板參數 – max66