Home > Software design >  Is it possible to "overload" the type deduced by auto for custom types in C ?
Is it possible to "overload" the type deduced by auto for custom types in C ?

Time:10-24

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.

CodePudding user response:

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.

  • Related