gpt4 book ai didi

c++ - 无法让 SFINAE 在功能检测器中工作

转载 作者:行者123 更新时间:2023-11-30 01:27:28 25 4
gpt4 key购买 nike

我一直在为最近发布的一些问题寻找一些解决方案,这些问题的原始发问者一直在尝试查询给定类中是否存在某个方法。我一直在尝试使用 SFINAE 方法开发解决方案,但不幸的是我总是一无所获。

这是我尝试的一种解决方案,它不适用于允许我们检测另一个类是否具有名为 function() 的方法的类。 :

#include <iostream>

using namespace std;

struct sample_class
{
void function() {}
};


template<typename T>
class test_size_call
{
private:
typedef char yes;
typedef char (&no)[2];
int tester[1];

template <unsigned int>
struct helper { static const unsigned int value = 1; };

template<typename R>
static yes test(int (&a)[helper<sizeof(std::declval<R>().function(), 0)>::value]);

/* template<typename R>
static no test(...); */

public:
static const bool value = (sizeof(test<T>(tester)) == sizeof(yes));
};


int main()
{
cout << "Has function() method: " << test_size_call<sample_class>::value << endl;
return 0;
}

结果,如果你取消对包罗万象的 test 的注释功能,不断出现 false .注释掉该函数后,我得到一个编译器错误,指出没有 test 的版本这需要 int (&)[1]争论。我很好奇为什么 declval<R>().function()似乎没有正确实例化。例如,如果我将其更改为非常明确的内容,例如 declval<T>().function()然后就可以了。不幸的是,这不是 SFINAE,因为如果类(class)没有 function()方法,而不是默默地失败,我得到一个编译器错误。

我确定我在这里遗漏了一些非常简单的东西。感谢您提供的任何帮助。

最佳答案

一定是你的编译器有问题,Clang 为以下代码正确打印了 10:

#include <utility>

template<typename T>
class test_size_call
{
private:
typedef char yes;
typedef char (&no)[2];
int tester[1];

template <unsigned int>
struct helper { static const unsigned int value = 1; };

template<typename R>
static yes test(int (&a)[helper<sizeof(std::declval<R>().function(), 0)>::value]);

template<typename R>
static no test(...);

public:
static const bool value = (sizeof(test<T>(tester)) == sizeof(yes));
};

#include <iostream>

struct sample_class
{
void function() {}
};

struct sample_class2{};

int main()
{
std::cout << "Has function() method: " << test_size_call<sample_class>::value << '\n';
std::cout << "Has function() method 2: " << test_size_call<sample_class2>::value << '\n';
return 0;
}

虽然 GCC 4.5.1 does not .请注意,它已在 GCC 4.7 中修复,正如所指出的那样 here .

关于c++ - 无法让 SFINAE 在功能检测器中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8913421/

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