【问题标题】:Why is the pointer in the argument required during SFINAE?为什么在 SFINAE 期间需要参数中的指针?
【发布时间】:2018-12-17 03:00:12
【问题描述】:

为什么我需要* 才能使checker 成为在线指针

template <typename C> static yes test( checker<C, &C::helloworld>* );

为了使编译时间扣除正常工作,输出1 0?

当我删除* 时,输出为0 0

#include <iostream>

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

// SFINAE test
template <typename T>
class has_helloworld
{
    typedef char                yes;
    typedef struct {char _[2];}  no; 

    template <typename C, int (C::*)()> struct checker;

    template <typename C> static yes test( checker<C, &C::helloworld>* );
    template <typename C> static no  test(...);

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

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

这是我尝试将这两个帖子放在一起的练习:

Is it possible to write a template to check for a function's existence?

Check if a class has a member function of a given signature

【问题讨论】:

    标签: c++ templates sfinae c++03 c++98


    【解决方案1】:

    因为它被称为test&lt;T&gt;(0),如果test 将指针作为参数类型(如checker&lt;C, &amp;C::helloworld&gt;*),则0 可以作为空指针被接受。

    如果您删除* 以使参数类型为checker&lt;C, &amp;C::helloworld&gt;test&lt;T&gt;(0) 只能匹配test(...),那么您将始终得到0 的结果。

    【讨论】:

    • 赞成解释这个谜团,同时又不失 C++ 的神秘主义。
    猜你喜欢
    • 2010-10-28
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2013-04-09
    • 1970-01-01
    相关资源
    最近更新 更多