以下代码运行输出:
A(const T&)
#include <iostream> #include <cstddef> template<class T> class A { public: A(const T& t) : val_(t) { std::cout << "A(const T&)" << std::endl; } private: const T& val_; }; template<> class A<const char *> { public: A(const char* t) : val_(t) { std::cout << "A(const char*)" << std::endl; } private: const std::string val_; }; template<class T> void foo(const T& t) { A<T> bar(t); } int main() { foo("Hello"); system("pause"); return 0; }
foo( "Hello" ); 并没有匹配偏特化的模板template<> class A<const char*>,这是因为"Hello"是一个字符常量,其类型是 const char[6],所以不能与这个模板要求的模板参数匹配。要正确匹配则需要将const char[6]转换到const char*。
如下代码则可以正确解析:
#include <iostream> #include <cstddef> // compile-time type transformation template<typename T> struct ptr_decay { typedef T type; }; template<typename T> struct ptr_decay<T[]> { typedef T* type; }; template<typename T, std::size_t N> struct ptr_decay<T[N]> { typedef T* type; }; template<typename T> class A { public: A() { std::cout << "A<T>::A()\n"; } }; template<> class A<const char *> { public: A() { std::cout << "A<const char*>::A()\n"; } }; template<typename T> void foo(const T& t) { // adjust type manually (array-to-pointer conversion) ... typedef typename ptr_decay<const T>::type decayed_t; A<decayed_t> a; // note: ^^^^^ (added const) } int main() { foo("Hello"); system("pause"); return 0; }
发表于 @ 2009年05月20日 10:07:00 | 评论( loading... ) | 编辑| 举报| 收藏