根据“Which <type_traits> cannot be implemented without compiler hooks?”,如果没有编译器内在函数,就不可能在C ++ 03中实现is_pod。我想到了一种可能的方法:C ++ 03不允许具有非平凡构造函数的成员的联合。是否可以使用SFINAE来检测这一点而不会抛出编译器错误?
我尝试了以下和许多变体,但无法使其发挥作用。它总是抛出错误或返回无效的答案。
#include <cstdio>
template <typename T>
class is_pod
{
template <typename U, void (U::*)()> struct Check;
template <typename U> union Union { U u; void member(); };
template <typename U> static char func(Check<Union<U>, &Union<U>::member> *);
template <typename U> static char (&func(...))[2];
public:
enum { value = sizeof(func<T>(0)) == sizeof(char) };
};
struct Meow { };
struct Purr { Purr() { } };
int main()
{
std::printf("%d\n", is_pod<Meow>::value);
std::printf("%d\n", is_pod<Purr>::value);
return 0;
}