template <typename T> struct A { operator auto() { return T{}; } }; 

What does "auto operator" mean? How does it differ from an explicit operator auto() ? When do they apply?

    1 answer 1

     // 1 struct widget { operator int() { return 10; } }; // 2 struct widget2 { operator auto() { return std::string{"hello"}; } }; // 3 struct widget3 { explicit operator int() { return 10; } }; // пример из вопроса template <typename T> struct A { // метод для преобразования объектов типа A<T> // в тип T (выведено) operator auto() { return T{}; } }; int main() { widget w; int wint = w; // ok widget2 w2; std::string wstr = w2; // ok widget3 w3; int w3int = w3; // error int w3inte = static_cast<int>(w3); // ok A<std::string> as; std::string asstr = as; // ok int asint = as; // error } 
    1. User defined transforms . It is possible to define a method for converting a custom type to another type.

    2. Type inference with auto . Like any other function, auto applies to converters.

    3. Explicit specifier . (for conversion functions) indicates to the compiler that the conversion function should not be considered for implicit type conversions.


    Starting with the C ++ 14 standard, the auto keyword can be used for the return value type of a function, indicating that the return value type should be inferred. Along with this, auto can be used in conversion operators (also starting with C ++ 14).

    There is one exception, auto cannot be used in template conversion operators. template <typename U> operator auto() { return 1; } template <typename U> operator auto() { return 1; } - will not compile.

    In the example from the question operator auto() { return T{}; } operator auto() { return T{}; } . The conversion operator is not a template, the requirements for type deduction are met (all return s have the same type) - the type can be displayed. The type will be displayed as T and this conversion operator can be considered as operator T{ return T{}; } operator T{ return T{}; }

    • Could you add an answer to why you can use auto in this context? Links are, of course, good, but it is advisable to quote in the answer itself - cpp questions
    • @cppquestions, updated - acade