【发布时间】:2018-02-19 14:35:55
【问题描述】:
您好,我试图使用 SFINAE 检查类中是否存在变量并使用它来定义我应该使用哪个朋友,我发现当我从 has_helloworld 检查值时,它无法扣除实际值。这是预期的吗? 我怎么能实现类似的东西? 这样的输出结果应该是:
0
1
但是当我再次放朋友时,它会是
1
1
我在 gcc 上使用 c++03。
#include <iostream>
#include <string>
template <typename T>
class has_helloworld
{
template <typename C> static char (&f( __typeof__(&C::helloworld) ) )[1] ;
template <typename C> static char (&f(...))[2];
public:
static const bool value = sizeof(f<T>(0)) == 2 ;
};
template <class T, const bool>
class FriendOption{public: void t (){std::cout<< "genericFriend"; }};
template <class T>
class FriendOption<T, false> {public: void t (){std::cout<< "false friend"; }};
template <typename T>
class Hello
{
typedef T field_type;
static const bool test = has_helloworld<field_type>::value;
//friend class FriendOption<field_type, test >;
public:
int helloworld() { return 0; }
};
class OTF {
public:
int helloworld() { return 0; }
};
class test : public Hello <test>
{};
struct Generic {};
int main(int argc, char *argv[])
{
std::cout << has_helloworld<test>::value << std::endl;
std::cout << has_helloworld<Generic>::value << std::endl;
return 0;
}
【问题讨论】:
标签: c++ templates sfinae c++03