gpt4 book ai didi

C++ SFINAE:const char[] 与 std::string 的 is_constructible

转载 作者:太空狗 更新时间:2023-10-29 20:34:14 25 4
gpt4 key购买 nike

我正在尝试禁用具有非 std::string 可构造类型的 ctor。我的第一次尝试是这样的:

#include <iostream>

struct A
{
template <typename U, typename = typename std::enable_if<std::is_constructible<std::string, U>::value>::type>
A(U&& val)
{
std::cout << "A(std::string&& val)" << std::string(std::forward<U>(val)) << std::endl;
}

template <typename U, typename = typename std::enable_if<not std::is_constructible<std::string, U>::value>::type>
A(U&& val)
{
std::cout << "A(int&& val)" << val << std::endl;
}
};

int main()
{
A a1(1);
A a2("hello");
A a3(std::string("hello"));
}

但是编译失败了

A a1(1);

错误信息如下:

error C2535: 'A::A(U &&)': member function already defined or declared (live example).

这意味着,SFINAE 的两个条件都成功并且两个 ctors 都被使用。

我继续尝试以下方法:

#include <iostream>

struct A
{
template <typename U>
A(U&& val, typename std::enable_if<std::is_constructible<std::string, U>::value>::type* = nullptr)
{
std::cout << "A(std::string&& val)" << std::string(std::forward<U>(val)) << std::endl;
}

template <typename U>
A(U&& val, typename std::enable_if<not std::is_constructible<std::string, U>::value>::type* = nullptr)
{
std::cout << "A(int&& val)" << val << std::endl;
}
};

int main()
{
A a1(1);
A a2("hello");
A a3(std::string("hello"));
}

幸运的是它可以编译并且工作正常(live example)。

到目前为止,我对第二种解决方案非常满意,但我真的不明白为什么使用模板化参数启用/禁用 ctor 的第一种方法不起作用。

最佳答案

条件不是都为真,那是不可能的。您可以放心,因为第二种方法有效,如果两者都成立,则不会发生这种情况。

重要的是要记住,默认模板参数不是函数模板签名的一部分。如果我们稍微减少两个 c'tors 到他们的签名,我们会得到这个:

template <typename U, typename>
A(U&& val)
{
}

template <typename U, typename>
A(U&& val)
{
}

两者是一模一样的。所以发生的是 U 的模板参数推导,并尝试进行替换以查看选择哪个重载。即使我们无法完成其中一个重载的模板参数推导(最后一个参数在其中一个中总是下落不明),但在尝试推导过程时,我们仍然会找到两个具有相同签名的模板。所以程序变成病式。

第二种方法可行,因为签名本身取决于正在评估的 enable_if。这就是为什么两个重载之一将始终被静默删除,就好像它从未存在过一样。

关于C++ SFINAE:const char[] 与 std::string 的 is_constructible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49975035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com