【发布时间】:2016-10-30 13:35:29
【问题描述】:
我正试图绕开 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,这可能是一个函数,但不一定是。 -
好点!谢谢!
标签: c++ templates metaprogramming sfinae decltype