Reputation: 6194
I was wondering whether a return type deduction in an assignment is possible in C++14 in some way. It feels redundant to type the <int>
after the return_five
function name. Thus, in other words, can the compiler use information from the left hand side of the assignment?
#include <iostream>
#include <string>
template<typename T>
auto return_five()
{
return static_cast<T>(5);
}
int main()
{
int five_int = return_five(); // THIS DOES NOT WORK
// int five_int = return_five<int>(); // THIS WORKS
std::cout << "Five_int = " << five_int << std::endl;
return 0;
}
Upvotes: 2
Views: 450
Reputation: 63124
Well, this works :
struct return_five {
template <class T>
operator T() const { return 5; }
};
int main (int, char**) {
int five_int = return_five();
std::cout << five_int << '\n';
}
Hint : you probably don't want to actually use that in production code.
Upvotes: 0
Reputation: 9705
Nope, but this is the best you can do:
int main() {
auto five_int = return_five<int>();
// ...
}
Upvotes: 1
Reputation: 1382
This is not possible. Template parameters of functions are only deduced from function arguments, not from return types (unfortunately).
Possibly not of much interest to you, but a way to deduce the template parameters is the following:
template<typename T>
void return_five(T& value)
{
value = static_cast<T>(5);
}
...
int five_int;
return_five(five_int);
Upvotes: 0
Reputation: 234695
C++ ain't VBA: the thing on the left hand side of the assignment is not used to deduce the type of the right hand side.
So the compiler requires an explicit type for return_five()
. You inform the compiler of the type by writing return_five<int>()
.
Upvotes: 5
Reputation: 76519
It's not so much return type deduction as it is templating the return type:
template<typename T>
T return_five()
{
return 5;
}
Upvotes: 0