簡體   English   中英

Class 模板參數推導——為什么這里會失敗?

[英]Class template argument deduction - why does it fail here?

為什么以下 CTAD 嘗試編譯失敗?

template <typename T> struct C { C(T,T) {} };
template <> struct C<int> { C(int) {} };

C c(1);  //error: template argument deduction failure

我原以為會推導出構造函數 C(int) 。

只為主模板中的構造函數生成隱式推導指南,而不為特化的構造函數生成。

您需要明確添加扣除指南:

C(int) -> C<int>;

您可以通過在主 class 模板中添加轉換構造函數解決此問題,如下所示:

template <typename T> struct C 
{ public:
    C(T,T) {} 
    
    //PROVIDE CONVERTING Constrcutor(with single parameter)
    C(T)
    {
        std::cout<<"Constrcutor called"<<std::endl;
    }
    
};
template <> struct C<int> { C(int) {
    std::cout<<"specialiazation constructor called"<<std::endl;
} };


int main()
{
    C c(1);  //this works now 

    return 0;
}

注意:此解決方案可能會導致對非 int 類型的單參數構造函數進行不必要的使用。 如果您不希望這樣,則不應使用它。

我添加了答案,以便人們知道它適用於手頭的問題。

暫無
暫無

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

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