Search code examples
c++templatestype-deduction

Template type deduction when converting from one type to another


I want to write a simple wrapper for the static_cast operator. My first attempt on the same is as shown below:

template <typename ForConvert, typename ToConvert>
ToConvert Convert(ForConvert val)
{
    return static_cast<ToConvert> (val);
}

And now I can use it like

auto x = 25;
auto y = Convert<int, float>(x);

Is there a way for the ForConvert part to be implicit? I want to be able to use the convert function like this :

auto x = 25;
auto y = Convert<float>(x);

Is there a way/technique(when defining the template function) so that compiler is able to deduce the type of x so that I shouldn't have to specify it explicitly? In a way I think I am asking how static_cast itself is implemented :-)


Solution

  • Reverse the order of the template parameters.

    template <typename ToConvert, typename ForConvert>
    ToConvert Convert(ForConvert val)
    {
        return static_cast<ToConvert> (val);
    }
    

    Now if you write

    Convert<float>(x)
    

    the float is used to fill in the first template parameter, ToConvert, and ForConvert is deduced from x since it's not given explicitly.