gpt4 book ai didi

c++ - 模板 : Deduction of array size failed

转载 作者:行者123 更新时间:2023-11-30 01:43:58 24 4
gpt4 key购买 nike

我试图将要处理的元素类型限制为 std::array<std::string,N>> , 但 N 的模板替换失败。

main.cpp:10:1: note:   template argument deduction/substitution failed:
main.cpp:31:34: note: couldn't deduce template parameter 'N'
print(word.begin(),word.end());

我的尝试如下。

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <boost/range/iterator_range.hpp>

template<typename ForwardIterator,std::size_t N>
typename std::enable_if<std::is_same<typename ForwardIterator::value_type,std::array<std::string,N> >::value >::type
print(ForwardIterator begin, ForwardIterator end)
{
for( auto const & arr : boost::make_iterator_range(begin,end) )
{
for( auto const & item : arr)
{
std::cout<<item<<' ';
}
std::cout<<'\n';
}
}

int main()
{
std::vector<std::array<std::string,2>> word;
word.push_back( {{"hello","Hi"}} );
word.push_back( {{"b","bye"}} );
print(word.begin(),word.end());
}

Demo on Coliru

最佳答案

你必须改变你的方法,而不是将类型与未知大小的数组进行比较(也就是说,编译器无法判断 N 你在想什么),验证是否类型本身可以推导为数组:

#include <array>
#include <iterator>
#include <type_traits>
#include <string>

template <typename T, typename A>
struct is_std_array : std::false_type {};

template <typename T, std::size_t N>
struct is_std_array<T, std::array<T,N>> : std::true_type {};

template<typename ForwardIterator>
auto print(ForwardIterator begin, ForwardIterator end)
-> typename std::enable_if<
is_std_array<std::string, typename std::iterator_traits<ForwardIterator>::value_type>::value
>::type
{

}

另外,不是 std::iterator_traits 的用法。

DEMO

关于c++ - 模板 : Deduction of array size failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965990/

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