问题描述
FrançoisAndrieux 为.我试图像这样回答他:
François Andrieux gave me a good workaround for this Visual Studio 2017 problem. I was trying to build on his answer like so:
template<class T, size_t N>
ostream& vector_insert_impl(ostream& lhs, const char*, const T& rhs)
{
return lhs << at(rhs, N);
}
template<class T, size_t N, size_t... I>
ostream& vector_insert_impl(ostream& lhs, const char* delim, const T& rhs)
{
return vector_insert_impl<T, I...>(lhs << at(rhs, N) << delim, delim, rhs);
}
template <typename T, size_t... I>
ostream& vector_insert(ostream& lhs, const char* delim, const T& rhs, index_sequence<I...>)
{
return vector_insert_impl<T, I...>(it, delim, rhs);
}
主要区别在于,递归结束"模板函数实际上将最后一个值插入到ostream
,而不是定界符中,而不是无操作.但是当我尝试编译它时,我得到了错误:
The key difference is that the "end of recursion" templated function actually inserts the last value into the ostream
, and not the delimiter rather than being a no-op. But when I try to compile this I get the error:
我认为可变长度模板函数被认为是3 类公民,而固定长度模板函数将始终是首选.该首选项在这里似乎无效.是否有解决方法将迫使编译器选择我的递归结束"功能,从而使我避免插入定界符?
I thought variable length template functions were considered 3 class citizens and fixed length template functions would always be preferred. That preference doesn't appear to be in effect here. Is there a workaround which will force the compiler to choose my "end of recursion" function enabling me to avoid inserting the delimiter?
推荐答案
您可以添加"Next
"元素
template <typename T, std::size_t N>
std::ostream & vector_insert_impl (std::ostream & lhs, char const *, T const & rhs)
{
return lhs << at(rhs, N);
}
// ..................................vvvvvvvvvvvvvvvv
template <typename T, std::size_t N, std::size_t Next, std::size_t ... I>
std::ostream & vector_insert_impl (std::ostream & lhs, char const * delim, T const & rhs)
{ // ............................vvvv
return vector_insert_impl<T, Next, I...>(lhs << at(rhs, N) << delim, delim, rhs);
}
但是,如果可以使用C ++ 17,我想if constexpr
是更好的解决方案
but, if you can use C++17, I suppose if constexpr
is a better solution
template <typename T, std::size_t N, std::size_t ... Is>
std::ostream & vector_insert_impl (std::ostream & lhs, char const * delim, T const & rhs)
{
if constexpr ( sizeof...(Is) )
return vector_insert_impl<T, Is...>(lhs << at(rhs, N) << delim, delim, rhs);
else
return lhs << at(rhs, N);
}
这篇关于重载可变长度模板函数的递归结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!