gpt4 book ai didi

c++ - 重载可变长度模板函数的递归结束

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:37:22 25 4
gpt4 key购买 nike

François Andrieux给了我一个很好的解决方法 this Visual Studio 2017 problem .我试图以他的回答为基础:

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 中。 , 而不是定界符 而不是空操作。但是当我尝试编译它时,我得到了错误:

error C2668: vector_insert_impl: ambiguous call to overloaded function (compiling source file ....\src\STETestbed\Test.cpp)
note: could be std::ostream &vector_insert_impl<T,2,>(std::ostream &,const char *,const T &)
note: or std::ostream &vector_insert_impl<T,2>(std::ostream &,const char *,const T &)

我认为可变长度模板函数被认为是 3rd 类公民,固定长度模板函数总是首选。这种偏好在这里似乎没有生效。是否有一种解决方法可以强制编译器选择我的“递归结束”函数,从而避免插入定界符?

最佳答案

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 是一个更好的解决方案

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);
}

关于c++ - 重载可变长度模板函数的递归结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56653029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com