注意C++模板函数的实参

#include <string>

#include <algorithm>

 

std::string& relabel(std::string &str)
{
    char c;

    c = str[0];
    std::replace(str.begin(), str.end(), c, 'a');

    std::replace(str.begin(), str.end(), str[1], 'b');

    return str;

}

 

relabel(std::string("123321")),返回值是"ab332a"。

第一句std::replace()将两个'1'改为'a';第二句std::replace()只将第一个'2'改为'b',第二个'2'仍保持原样,不符合调用目的。

注意:模板函数类似宏替换,如果实参的值在调用过程中被改变,有可能达不到调用模板函数的目的。但是有时这种替换又很有用,例如str.end()这样可以根据str动态变化的。

发布了43 篇原创文章 · 获赞 2 · 访问量 7万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章