5

考虑以下示例:

#include <string>
#include <sstream>

struct Location {
    unsigned line;

    template<typename CharT, typename Traits>
    operator std::basic_string<CharT, Traits>() const {
        std::basic_ostringstream<CharT, Traits> ss;
        ss << line;
        return ss.str();
    }
};

int main() 
{
    using namespace std::string_literals;

    Location loc{42};

    std::string s1 = "Line: "s.append(loc) + "\n"s; // fine
    //std::string s2 = "Line: "s + loc + "\n"s; // error
}

注释行导致编译错误:no match for 'operator+'. 为什么?我最初的想法是,它首先会operator std::string用于转换,然后执行对 的调用operator+,就像它对.append.

它只是隐式转换的一级,所以应该执行并且应该考虑到它,不是吗?

Live Demo

4

2 回答 2

2

您的运算符是模板化的,因此需要推导出模板参数。你不能这样做,因为编译器试图匹配basic_string<_CharT, _Traits, _Alloc>你的Location,它失败了。

所以问题是重载,而不是转换,因为代码实际上从未达到那个点。

改变这个:

std::string s2 = "Line: "s + loc + "\n"s;

对此:

std::string s2 = "Line: "s + std::string(loc) + "\n"s;

你应该没问题,因为如果你仔细查看编译器错误,它会提到:

template argument deduction/substitution failed:
prog.cc:22:32: note:   'Location' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>'
   std::string s2 = "Line: "s + loc + "\n"s; // error
                                ^~~

和其他类似的消息。

于 2017-10-20T06:29:00.977 回答
0

显式转换为 std::string 对我有用:https ://godbolt.org/g/WZG78z

    std::string s2 = "Line: "s + std::string(loc) + "\n"; // was error
于 2017-10-20T06:26:17.283 回答