Why can't C++ deduce template type from assignment?

后端 未结 5 1065
盖世英雄少女心
盖世英雄少女心 2020-12-06 09:39

int x = fromString(\"test\") :could not deduce template argument for \'ValueType\'

int x = fromString(\"test\") : works

5条回答
  •  执笔经年
    2020-12-06 10:41

    The return type of a function is dependent on overload resolution, not the other way around.

    There is a trick that works though: operator= usually exists only for equal LHS/RHS argument types, except when an explicit operator= is defined (whether as standalone or as a member does not matter).

    Thus, overload resolution will find operator=(int &, int), and see if the return value from your function is convertible to int. If you return a temporary that has an operator int, this is an acceptable resolution (even if the operator int is in the generic form of a template operator T).

    Thus:

    template
    U convert_impl(T const &t);
    
    template
    struct convert_result {
        convert_result(T const &t) : t(t) { }
        template operator U(void) const { return convert_impl(t); }
        T const &t;
    };
    
    template
    convert_result convert(T const &t) { return t; }
    

提交回复
热议问题