繁体   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