问题
I am just curious:
On the following sample I show what I mean in place of /*implicit*/
.
Is there a workaround to leave it blank? typename T cannot be first as you can see.
template<typename C1, typename C2, typename T = decltype(typename C1::value_type() * typename C2::value_type())>
T dot(const C1 &v1, const C2 &v2);
int main()
{
std::vector<float> vec1;
std::vector<double> vec2;
// typical:
auto result1 = dot(vec1, vec2); // auto -> double
// avoid numerical unstable situations:
auto result2 = dot</*implicit*/,/*implicit*/,long double>(vec1, vec2); // auto -> long double
//auto result2 = dot<decltype(vec1),decltype(vec2),long double>(vec1, vec2);
}
In the last line, I provide a solution witch is not super-bloated.
回答1:
Just reorder the parameters, and go conditional:
// short notation for `std::declval<typename C::value_type&>()`
template<class C>
typename C::value_type& value_in();
// if T == void, find actual result type, else use T
template<class T, class C1, class C2>
using DotResult = typename std::conditional<std::is_void<T>::value,
decltype(value_in<C1>() * value_in<C2>()), T>::type;
// void can't be a valid value_type
template<class T = void, class C1, class C2>
DotResult<T,C1,C2> dot(C1 const& c1, C2 const& c2);
However, I have to admit... I really don't see the use for it - you could just cast the result instead, or implicitly convert it... long double x = dot(v1, v2);
来源:https://stackoverflow.com/questions/16199863/skip-earlier-implicit-template-parameter-but-not-later-in-a-template-parameter