簡體   English   中英

使用依賴類型的模板構造函數的專用模板類(從一般情況下下降)

[英]Specialized template class (descended from general case) with a template constructor using a dependent type

我需要使模板化類的構造函數采用從屬類型(在模板化類類型上)。 除非我對模板化類有專門的知識,否則這很好用,在這種情況下似乎找不到構造函數。 而且,如果我在專用子類中重新實現構造函數,則似乎無法通過構造函數或直接初始化基類。

有什么辦法可以在班級外部保留這個相對狹窄的接口嗎?

class T1 {};
class T2 {};

// KeyType
template <typename SELECT>
class KeyType {
};

// Declarations
template <typename SELECT = T1>
class TestTemplate {
protected:
    TestTemplate() {}
    KeyType<SELECT> k;
public:
    TestTemplate(KeyType<SELECT> const &key) : k(key) {}
};

template <>
class TestTemplate<T2> : public TestTemplate<T1> {
};


int main() {

    KeyType<T2> key;
    TestTemplate<T2> foo(key);
    return 0;
}

盯着它為一個位后,我認識到的問題是,我不能只轉換任意的KeyType<T2>到一個KeyType<T1>TestTemplate<T1>基類。

g ++給出:

g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In function 'int main()':
main.cpp:27:29: error: no matching function for call to 'TestTemplate<T2>::TestTemplate(KeyType<T2>&)'
     TestTemplate<T2> foo(key);
                             ^
main.cpp:20:7: note: candidate: TestTemplate<T2>::TestTemplate()
 class TestTemplate<T2> : public TestTemplate<T1> {
       ^
main.cpp:20:7: note:   candidate expects 0 arguments, 1 provided
main.cpp:20:7: note: candidate: constexpr TestTemplate<T2>::TestTemplate(const TestTemplate<T2>&)
main.cpp:20:7: note:   no known conversion for argument 1 from 'KeyType<T2>' to 'const TestTemplate<T2>&'
main.cpp:20:7: note: candidate: constexpr TestTemplate<T2>::TestTemplate(TestTemplate<T2>&&)
main.cpp:20:7: note:   no known conversion for argument 1 from 'KeyType<T2>' to 'TestTemplate<T2>&&'

構造函數根本不會在C ++中繼承,因此您的實例TestTemplate<T2>僅具有隱式聲明的構造函數(默認情況下,復制並移動它似乎是由於您發布的錯誤消息而引起)。 如果您假設在專門化模板時,專門化的模板會從正在專門化的模板繼承聲明和定義:事實並非如此。 您必須重新聲明並重新定義專用模板中的所有成員。

因此,在您的情況下,您必須將適當的構造函數添加到您的專用模板中,如下所示:

template <>
class TestTemplate<T2> : public TestTemplate<T1> {
public:
    TestTemplate<KeyType<T2> const &key) :
    TestTemplate<T1>(...) {}
};

由於基類TestTemplate<T1>沒有提供默認的構造函數,因此您必須調用該構造函數,但是,由於要引用的實例,因此尚不清楚要傳遞給它什么作為鍵參數。 KeyType<T2>而不是KeyType<T1>

如果您確實希望從TestTemplate<T1>繼承構造函數, TestTemplate<T1>可以using指令進行此using ,假設您使用的是C ++ 11:

template <>
class TestTemplate<T2> : public TestTemplate<T1> {
public:
    using TestTemplate<T1>::TestTemplate;
};

但不可否認,我對這里的語法不是100%的。

暫無
暫無

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

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