【问题标题】:Using SFINAE to select friend or base class c++x03使用 SFINAE 选择朋友或基类 c++x03
【发布时间】: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


    【解决方案1】:

    问题不在于朋友,而在于测试

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

    将全新类型 Hello&lt;field_type&gt; 传递给测试:

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

    Demo

    【讨论】:

    • 谢谢你,你是对的,这解决了我的问题并在静态变量上保持正确的值
    猜你喜欢
    • 2010-09-19
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    相关资源
    最近更新 更多