gpt4 book ai didi

c++ - 使用 SFINAE 选择 friend 或基类 c++x03

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:26 25 4
gpt4 key购买 nike

您好,我试图使用 SFINAE 检查类中是否存在变量并使用它来定义我应该使用哪个 friend ,我发现当我检查 has_helloworld 的值时,它无法扣除实际值。这是预期的吗?我怎么能实现类似的东西?这样的输出结果应该是:

0
1

但是当我再次放置 friend 时,它将是

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;
}

最佳答案

问题不在 friend 而是在测试

static const bool test = has_helloworld<field_type>::value

传全新类型Hello<field_type>测试:

static const bool test = has_helloworld<Hello<field_type>>::value;

Demo

关于c++ - 使用 SFINAE 选择 friend 或基类 c++x03,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48868404/

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