问题描述
template < typename InputIterator,typename ContainerType >
void Slice(InputIterator begin,InputIterator end,typename InputIterator::value_type delimiter,ContainerType& container)
{
using CharType = InputIterator::value_type;
InputIterator right = begin;
while (true) {
begin = find_if_not(right,end,[ delimiter ](CharType c) { return c == delimiter; });
if (begin == end) {
break;
} else {
right = find_if(begin + 1,[ delimiter ](CharType c) { return c == delimiter; });
container.push_back(std::basic_string< CharType >(begin,right));
}
}
}
template < typename InputIterator,InputIterator delimitersBegin,InputIterator delimitersEnd,ContainerType& container)
{...}
它适用于像
这样的调用std::string headers;
std::vector<std::string> rawHeaders;
Slice(headers.begin(),headers.end(),'\0',rawHeaders)
并且不适用于 const char*
:
auto begin = headers.c_str();
auto end = begin + headers.size();
Slice(begin,rawHeaders);
错误是(我将 MSVC2017 与 MSVC2013 工具链一起使用):
错误 C2780:'void Slice(InputIterator,InputIterator,ContainerType &)':需要 5 个参数 - 提供 4 个
错误 C2893:无法专门化函数模板 'void Slice(InputIterator,InputIterator::value_type,ContainerType &) 使用以下模板参数: 'InputIterator=const char *' 'ContainerType=std::vectorstd::string,std::allocator<_ty>'
更新:添加了函数体。 目前最好不要使用像 std::span 这样的附加功能。 我希望有以下字符串构造函数:
template< class InputIt >
basic_string( InputIt first,InputIt last,const Allocator& alloc = Allocator() );
更新 2:仍然不起作用,但出于不同的原因,我尝试更改分隔符类型:
template < typename InputIterator,typename ContainerType >
void Slice(
InputIterator begin,typename std::iterator_traits< InputIterator >::value_type delimiter,//typename InputIterator::value_type delimiter,ContainerType& container)
{
using CharType = typename std::iterator_traits< InputIterator >::value_type;
现在它说:
错误 C3861:“find_if_not”:未找到标识符。请参阅使用 [_Ty=std 编译的函数模板实例化 'void StringUtils::Slice
还有:
错误 C3861:'find_if':未找到标识符
解决方法
SFINAE 开始。签名
template < typename InputIterator,typename ContainerType >
void Slice(InputIterator begin,InputIterator end,typename InputIterator::value_type delimiter,ContainerType& container)
不是可能的候选对象,因为 ::value_type
中没有嵌套成员 const char*
。
你可能想要这个签名:
template < typename InputIterator,typename std::iterator_traits<InputIterator>::value_type delimiter,ContainerType& container)
,
您可以使用 std::span
。
将其包裹在您的指针上。它重量轻,速度快。 我不确定它是否已经在您的工具链中。