C++ template -- 字符串作为函数模板实参

本文探讨了C++中模板参数的使用,特别是在引用参数与非引用参数情况下,不同类型参数如何进行匹配及类型推导的过程。通过具体示例说明了数组到指针的隐式转换现象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.

#include <string>

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

int main()
{
    std::string s;

    ::max("apple","peach");   // OK: same type
    ::max("apple","tomato");  // ERROR: different types
    ::max("apple",s);         // ERROR: different types
}

一个char const[6],一个char const[7]..."apple","tomato"不同...

 

2.

#include <string>

// note: nonreference parameters
template <typename T>
inline T max (T a, T b)
{
    return  a < b  ?  b : a;
}

int main()
{
    std::string s;

    ::max("apple","peach");    // OK: same type
    ::max("apple","tomato");  // OK: decays to same type (退化到相同的类型)
    ::max("apple",s);              // ERROR: different types
}

 

3.

#include <typeinfo>
#include <iostream>

template <typename T>
void ref (T const& x)
{
    std::cout << "x in ref(T const&): " 
              << typeid(x).name() << '/n';
}

template <typename T>
void nonref (T x)
{
    std::cout << "x in nonref(T):     "
              << typeid(x).name() << '/n';
}

int main()
{
    ref("hello");
    nonref("hello");
}

 

Under Solaris:

x in ref(T const&): char[6]
x in nonref(T):     const char*

 

对于非应用类型参数,在推演的过程中,可能会发生数组到指针的转化!(array-to-point)...

 

 黄山鳌鱼背

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值