Conversion operator template specialization

后端 未结 2 1572
天命终不由人
天命终不由人 2020-12-25 13:23

Here\'s a largely academic exercise in understanding conversion operators, templates and template specializations. The conversion operator template in the following code wo

2条回答
  •  春和景丽
    2020-12-25 14:08

    static_cast here is equivalent of doing std::string(a).

    Note that std::string s = std::string(a); doesn't compile either. My guess is, there are plenty of overloads for the constructor, and the template version can convert a to many suitable types.

    On the other hand, with a fixed list of conversions, only one of those matches exactly a type that the string's constructor accepts.

    To test this, add a conversion to const char* - the non-templated version should start failing at the same place.

    (Now the question is why std::string s = a; works. Subtle differences between that and std::string s = std::string(a); are only known to gods.)

提交回复
热议问题