簡體   English   中英

使用 std::enable_if 禁用構造函數

[英]Disabling a constructor using std::enable_if

我的目標是創建我自己的std::basic_string類似物,但有一些附加條件。 我希望我的AnyString<CharType, Traits>可以從std::basic_string<CharType, AnyOtherTraits, AnyAlloc>但我想為某些 CharType 禁用此構造函數,這樣basic_string<CharType>不存在(編譯)。

我試圖做這樣的事情:

    template<typename OtherTraits, typename Alloc, typename = 
        std::enable_if_t<!std::is_array_v<char_type> && 
        std::is_trivial_v<char_type>                 && 
        std::is_standard_layout_v<char_type>>>
    AnyString(const std::basic_string<char_type, OtherTraits, Alloc>&);

我有ColouredChar ,它不符合enable_if_t中列出的條件。

現在,當我試圖調用禁用的構造函數時:

std::basic_string<ColouredChar> de("string"_purple);
ColouredString d(de);

我不僅從basic_string得到編譯錯誤,而且還有一個非常奇怪的錯誤,告訴我完全不同的 PRIVATE 構造函數構造函數不能從basic_string轉換它的參數。

有什么方法可以使這些編譯錯誤更具可讀性嗎? 或者至少解釋這里是否有什么值得擔心的。

使用概念(不是你的特征)的構造函數限制的基本示例

#include <type_traits>
#include <string>

// declare your own concept
template<typename type_t>
concept my_concept = std::is_convertible_v<type_t, std::string>; // just a demo concept
    
class ColouredString
{
public:
    // then you can limit your constructor to types satisfying that concept
    ColouredString(const my_concept auto& /*arg*/)
    {
    }

    ~ColouredString() = default;
};


int main()
{
    // ColouredString str{ 1 };
    ColouredString str{ "hello world!" };

    return 0;
}

只是要指出,除了存在答案之外,您不需要定義一個概念來在 require-clause 中使用它

class ColouredString{
public:
    template<typename T>
    requires (std::is_convertible_v<T, std::string>)
    ColouredString(const T&){}
};

並且已經有一個std::convertable_to概念

class ColouredString{
public:
    ColouredString(const std::convertible_to<std::string> auto&){}
};


fwiw,既然你說

我想為某些 CharType 禁用此構造函數,以便 basic_string 不存在

您的代碼使用string構造函數失敗可能只是因為您嘗試創建一個。 它與ColouredString

std::basic_string<ColouredChar> de("string"_purple); // it already fail here
ColouredString d(de); 

暫無
暫無

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

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