[英]Problem while checking if function exist in c++
I've found some very interesting c++ code on stackoverflow and I'm very confused about it because as author says it should work and it fails on my gcc 4.5.1 and 4.4 :( The goal is to check if class contain or not a specific method. 我在stackoverflow上发现了一些非常有趣的c ++代码,我对此非常困惑,因为作者说它应该工作并且它在我的gcc 4.5.1和4.4上失败:(目的是检查类是否包含具体方法。
the code is: 代码是:
#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;
}
I've got compiler error: 我有编译器错误:
ISO C++ forbids in-class initialization of non-const static member 'test'
ISO C ++禁止非const静态成员'test'的类内初始化
Additional as some comment says - I can change 'typeof(&C::helloworld)' to 'char[sizeof(&C::helloworld)]' but then my output is 另外正如一些评论所说 - 我可以将'typeof(&C :: helloworld)'更改为'char [sizeof(&C :: helloworld)]'然后我的输出是
1
1
what is wrong, because only one class has helloworld function 有什么不对,因为只有一个类有helloworld功能
Is there any method to make it working? 有什么方法可以使其正常工作吗? Addition I would be very thankfull if somebody could explain what exactly makes this command:
另外,如果有人能解释一下这个命令的确切含义,我将非常感激:
test( char[sizeof(&C::helloworld)] ) ;
Thank you very much :) 非常感谢你 :)
Your trouble is with the use of the integral zero and typeof. 你的麻烦在于使用积分零和类型。 Using MSVC10, decltype, and nullptr, it's a trivial modification for this code to print the correct values.
使用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;
}
I'm not an expert on typeof, but something like this should be doable: 我不是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 };
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.