Search code examples
c++operator-overloadingtype-deduction

Is it possible to "overload" the type deduced by auto for custom types in C++?


Not sure whether "overloading" is the proper term, however I am curious whether it is possible to make expressions of a given type to automatically convert to other type?

Possible motivation:

template <typename T> Property {
// implement the desired behavior
};

class SomeClass {
// ...
Property<SomeType> someProperty;
// ...
};

SomeClass someInstance{ ... };
auto someVariable = someInstance.someProperty; // Type of some variable will be Property<T>

If I take some effort, I can disallow constructor and assignment of Property and use

SomeType someVariable = someInstance.someProperty; 

However, I am curious whether it is possible to make

auto someVariable = someInstance.someProperty;

such the the type of someVariable is SomeType and not Property<SomeType>.

Thanks.


Solution

  • No, that is not possible. auto will deduce to the (decayed) type of the right-hand side and there is no way to affect this deduction.

    You can however of course write a function template X such that

    auto someVariable = X(someInstance.someProperty);
    

    will result in the type you want, basically without any restrictions on the possible type transformations made by X.