《C++ template》书上的一个例子,百思不得其解
下面这个模板是《C++ template》一书 15.2.2 节的一个例子,用来判断一个给定的类型是不是一个类(class 或者 struct)
namespace book_cpp_template{
template<typename T>
class IsClassType {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*);
template<typename C> static Two test(...);
public:
enum { Yes = sizeof(IsClassType<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
} // namespace book_cpp_template
可问题是,我目测这段代码无法通过编译,事实也的确如此,使用了这个模板的代码根本通不过编译,起初我怀疑是书上打印错了,到指定的示例源码网站下载了代码,也是这样的,实在没招了,求助ing..... 模板 类型 IsClassT C++?template
[解决办法]
改成这样就可以了enum { Yes = sizeof(test<T>(0)) == 1 };
[解决办法]
int指的是 成员变量的类型是int;
struct test
{
int a;
};
int main()
{
int test::*p = &test::a;
test x;
x.a = 19;
printf( "%d\n" , x.*p );
}