编写一个一元元函数add_const_ref<T>,如果T是一个引用类型,就返回T,否则返回T const&。
#ifndef T1_H #define T1_H template <typename T> struct add_const_ref { typedef const T& type_value; }; template <typename T> struct add_const_ref<T&> { typedef T type_value; }; template <typename T> struct is_const { static const bool value = false; }; template <typename T> struct is_const<T&> { static const bool value = true; }; #endif #include <iostream> #include "t1.h" struct A { }; int main() { int i = 2; add_const_ref<int>::type_value j = i; i = j; std::cout << typeid(j).name() << '\n'; std::cout << is_const<add_const_ref<A>::type_value>::value << '\n'; return 0; }
我使用的IDE是vs2012,结果是
vs做的还不错,结果不需要运行就可以得到了....元编程的威力