我想圍繞SFINAE包裹我的頭。 我們正在使用它來檢查一個班級是否有一種名爲「乘客」的方法。SFINAE C++方法檢查
通過一些在線示例,我們構建了以下模板類。
#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?
你不檢查班級是否有成員功能'乘客'。你正在檢查它是否有一個「乘客」成員,這可能是一個功能,但不一定是。 – krzaq
好點!謝謝! –