template 模板使用

作者在 2010-07-02 19:56:08 发布以下内容
#include <string>

template <typename T>
inline T const& max(T a,T b)
{
    return a<b?b:a;
}

int main()
{
    std::string s;
    const char *a1="apple",*a2="peach";
    const char aa1[]="apple",aa2[]="peacha";
    ::max(a1,a2);
    ::max(aa1,aa2);
    ::max("apple","peach");
    ::max("apple","peacha");

    return 0;
}
 此时模板把 peacha 之类的认为是字符串,因此只是一个指针
#include <string>

template <typename T>
inline T const& max(T const& a,T const& b)
{
    return a<b?b:a;
}

int main()
{
    std::string s;
    const char *a1="apple",*a2="peach";
    const char aa1[]="apple",aa2[]="peacha";
    ::max(a1,a2);
    ::max(aa1,aa2);          // error
    ::max("apple","peach");
    ::max("apple","peacha"); // error

    return 0;
}
 此时两处error均是因为
error C2782: 'const T &__cdecl max(const T &,const T &)' : template parameter 'T' is ambiguous
        could be 'const char [7]'   or       'const char [6]'
也就是此时被认为是数组(地址确定的指针),因此认为长度不一致的数组认为不同的类型
技术 | 阅读 1947 次
文章评论,共0条
游客请输入验证码
浏览1936571次