gpt4 book ai didi

c++ - SFINAE 测试来自另一个命名空间的自由函数

转载 作者:可可西里 更新时间:2023-11-01 17:47:01 25 4
gpt4 key购买 nike

我试图想出一个 hack 来测试 std::isnan 是否在预处理器中没有特殊外壳编译器的情况下定义,并想出了以下内容,我希望它能正常工作.

#include <cmath>
#include <type_traits>

namespace detail {
using namespace std;

struct dummy {};
void isnan(dummy);

//bool isnan(float); // Just adding this declaration makes it work!

template <typename T>
struct is_isnan_available {
template <typename T1>
static decltype(isnan(T1())) test(int);
template <typename>
static void test(...);

enum { value = !std::is_void<decltype(test<T>(0))>::value };
};
}

int main() {
return detail::is_isnan_available<float>::value;
}

结果 it doesn't detect it .我知道某些 std::isnan 是在 ideone 上定义的,因为我手动测试过它。

当我uncomment the marked line above , 它有效。

我在这里错过了什么?如何解释这种行为?

最佳答案

事实是,using 指令不会将成员添加到当前命名空间,因此 std:: 成员仍然可以被该命名空间中的声明隐藏。

using std::isnan 的行为就像将导入的命名空间的成员添加到包含 use 位置和导入的命名空间的命名空间一样。 using 声明是命名空间中的普通声明,因此可以与后面的声明一起参与重载决议。

但是,正如评论中指出的那样,如果该函数不存在,则会产生错误。要解决这个问题,您需要 put it out of your detail:: namespace then .这应该有效,因为导入的定义将与 dummy 重载处于同一级别。您可以将重载带到全局命名空间,或者您可以创建一个辅助命名空间(在全局命名空间中)和 import both .

关于c++ - SFINAE 测试来自另一个命名空间的自由函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756779/

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