MyMSDN

MyMSDN记录开发新知道

模板类型推断的一个小问题

/*
 * type_infer_in_const_char_array.cpp
 *
 *  Created on: 2010-4-4
 *      Author: volnet
 *      Ref: http://topic.csdn.net/u/20100403/16/aebc3e87-ae49-4a18-ba0b-263348b512e3.html
 *      ShortRef: http://is.gd/be914
 */

#include <stdlib.h>
#include <iostream>
#ifdef _MSC_VER
#include <typeinfo.h>
#else
#include <typeinfo>
#endif

template <typename T>
int compare(const T &v1, const T &v2) {
    std::cout << "invoking compare ..." << std::endl;
    if(v1<v2) return -1;
    if(v2<v1) return 1;
    return 0;
}
int main()
{
    //error:
    // no matching function for call to `compare(const char[3], const char[6])'
    // compare("hi","world");
    compare<const char*>("hi","world");
    //what's the real type about "abcd"?
    // const char * or const char [n] ?
    std::cout << typeid("hi").name() << std::endl;        // char const [3]
    std::cout << typeid("world").name() << std::endl;    // char const [6]
    std::cout << typeid("dlrow").name() << std::endl;    // char const [6]
    // the compiler infer the typename T is char const [6]
    compare("world", "dlrow");
}


posted on 2010-04-05 00:28 volnet 阅读(293) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


特殊功能