我正在努力理解SFINAE。
我们正在使用它来检查一个类是否有一个名为“Passengers”的方法。
根据一些在线示例,我们构建了以下模板类:
#ifndef TYPECHECK
#define TYPECHECK
#include "../Engine/carriage.h"
namespace TSS{
template<typename T>
class has_passengers{
private:
typedef char one;
typedef struct{char a[2];} two;
template<typename C> static one test( decltype(&C::Passengers) );
template<typename C> static two test(...);
public:
static bool const value = sizeof(test<T>(0)) == sizeof(one);
};
template<typename T>
struct CarriageTypeCheck{
static_assert(has_passengers<T>::value, "Train initialized with illegal carriage");
};
}
#endif // TYPECHECK
我明白了两种测试方法中的任意一种是如何被选择的,但我不理解以下行为什么要将test<T>
初始化为0:
static bool const value = sizeof(test<T>(0)) == sizeof(one);
我看不出0对于检查的重要性。 另外,为什么要使用decltype?
Passengers
。你正在检查它是否有成员Passengers
,这可能是一个函数,但不一定是。 - krzaq