gpt4 book ai didi

c++ - 检查c++中是否存在函数时出现问题

转载 作者:行者123 更新时间:2023-11-28 03:54:23 25 4
gpt4 key购买 nike

我在 stackoverflow 上发现了一些非常有趣的 C++ 代码我对此很困惑,因为正如作者所说,它应该可以工作,但在我的 gcc 4.5.1 和 4.4 上失败了:(目标是检查类是否包含特定方法。

代码是:

#include <iostream>

struct Hello
{
int helloworld()
{ return 0; }
};

struct Generic {};


// SFINAE test
template <typename T>
class has_helloworld
{
typedef char one;
typedef long two;

template <typename C> static one test( typeof(&C::helloworld) ) ;
template <typename C> static two test(...);


public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};


int
main(int argc, char *argv[])
{
std::cout << has_helloworld<Hello>::value << std::endl;
std::cout << has_helloworld<Generic>::value << std::endl;
return 0;
}

我有编译器错误:

ISO C++ forbids in-class initialization of non-const static member 'test'

如一些评论所说的附加 - 我可以将 'typeof(&C::helloworld)' 更改为 'char[sizeof(&C::helloworld)]'但是我的输出是

1
1

怎么了,因为只有一个类有helloworld函数

有什么方法可以让它工作吗?另外,如果有人能解释这个命令的确切含义,我将非常感激:

test( char[sizeof(&C::helloworld)] ) ;

非常感谢:)

最佳答案

您的麻烦在于使用整数零和 typeof。使用 MSVC10、decltype 和 nullptr,只需对该代码进行微不足道的修改即可打印正确的值。

template <typename T>
class has_helloworld
{
typedef char one;
typedef long two;

template <typename C> static one test( decltype(&C::helloworld) ) ;
template <typename C> static two test(...);


public:
enum { value = std::is_same<decltype(test<T>( nullptr )), char>::value };
};


int main(int argc, char *argv[])
{
std::cout << has_helloworld<Hello>::value << std::endl;
std::cout << has_helloworld<Generic>::value << std::endl;
std::cin.get();
return 0;
}

我不是 typeof 方面的专家,但像这样的事情应该是可行的:

struct no_type {};
// SFINAE test
template <typename T>
class has_helloworld
{
template <typename C> static typeof(&C::helloworld) test( C* i );
template <typename C> static no_type test(...);


public:
enum { value = std::is_same<no_type, typeof(test<T>(0))>::value };
};

关于c++ - 检查c++中是否存在函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4200158/

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