为什么在 SFINAE 期间需要参数中的指针?
Why is the pointer in the argument required during SFINAE?
为什么我需要一个 *
来使 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
因为它被称为test<T>(0)
,如果test
以指针作为参数类型(如checker<C, &C::helloworld>*
),0
可以被接受为空指针。
如果你删除*
使参数类型为checker<C, &C::helloworld>
,test<T>(0)
只能匹配test(...)
那么你总是会得到结果0
.
为什么我需要一个 *
来使 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
因为它被称为test<T>(0)
,如果test
以指针作为参数类型(如checker<C, &C::helloworld>*
),0
可以被接受为空指针。
如果你删除*
使参数类型为checker<C, &C::helloworld>
,test<T>(0)
只能匹配test(...)
那么你总是会得到结果0
.