Reputation: 906
Type deduction fails for the following case. It compiles if I specify the template argument to someFunc. I definitely see how this is a weird case but it would be nice if I could get it to work. Is there an alternate way to formulate it that would compile without providing the template parameter? A C++17 solution is fine.
#include <type_traits>
template<typename T>
using choose_arg_type = typename std::conditional<std::is_fundamental<T>::value,T,const T &>::type;
template<typename T>
T someFunc(choose_arg_type<T> arg)
{
return arg + arg;
}
int main()
{
auto result = someFunc(0.0);
return 0;
}
Upvotes: 4
Views: 134
Reputation: 62613
No, choose_arg_type<T>
is in non-deduced context. There are quite a few duplicates already.
However, you can have two overloads, and SFINAE-enable them based on the type.
Upvotes: 0
Reputation: 181007
In
template<typename T>
T someFunc(choose_arg_type<T> arg)
T
is a dependent type. Because of that no type deduction will happen here. You can work around this issue by using SFINAE and introducing a set of overloads for when the type is fundamental or not. That would look like
template<typename T, std::enable_if_t<std::is_fundamental_v<T>, bool> = true>
T someFunc(T arg)
{
return arg + arg;
}
template<typename T, std::enable_if_t<!std::is_fundamental_v<T>, bool> = true>
T someFunc(const T& arg)
{
return arg + arg;
}
Upvotes: 5