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

    技术2024-08-13  74

    #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动态变化的。

    最新回复(0)