Casting for template function to work.

I'm having issues understanding what's the difference between this two implementations of tripleVal?

Why do I need to add the return casting to call the first function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template <class T,class U>
T tripleVal(U val)
{
    val = val * 3;
    return val;
}

template <class V>
V tripleVal2(V val)
{
    val = val * 3;
    return val;
}

int main()
{
    cout << tripleVal(5.5) << endl;// Error for this line of code tripleVal(5.5) 
    //only works if i add <int> or <double> like this tripleVal <double>(5.5)

    cout << tripleVal2(5.5) << endl; // works as per normal
}
> Why do I need to add the return casting to call the first function?

The template parameter T can't be deduced.

To allow deduction, write it as:

1
2
template < typename T > 
auto tripleVal( const T& val ) -> decltype( val*3 ) { return val * 3 ; }


Or, in C++14:
1
2
template < typename T > 
auto tripleVal( const T& val ) { return val * 3 ; }


Last edited on
Topic archived. No new replies allowed.