我正在尝试创建一个静态 vector vector ,我发现以下代码在 gcc-4.1.2 下编译和运行,但在 gcc-4.5.1 下它无法编译并显示消息
assign.cxx:19:48: error: no matching function for call to ‘to(boost::assign_detail::generic_list<std::basic_string<char> >&)’
谁能解释为什么会这样?如果您对如何做我正在尝试做的事情有任何其他建议,那么我会很高兴 :)。
#include <iostream>
#include <string>
#include <vector>
#include <boost/assign/list_of.hpp>
template <template <typename> class containerType, typename elemType>
containerType<elemType> to( boost::assign_detail::generic_list<elemType> list ) {
containerType<elemType> tempContainer = list;
return tempContainer;
}
static const std::vector<std::vector<std::string> > names = boost::assign::list_of
(to<std::vector>(boost::assign::list_of<std::string>("A")("B")("C") ))
(to<std::vector>(boost::assign::list_of<std::string>("D")("E")("F") ));
int main() {
for( std::vector< std::vector<std::string> >::const_iterator itVec = names.begin(); itVec != names.end(); ++itVec ) {
for( std::vector<std::string>::const_iterator itStr = itVec->begin(); itStr != itVec->end(); ++itStr ) {
std::cout << "Value is " << *itStr << std::endl;
}
}
return 0;
}
最佳答案
问题源于这样一个事实,即在您对 to<>()
的定义中, containerType
被声明为只有一个模板参数,而实际上是std::vector<>
有两个模板参数。
在 GCC 4.1.2 中编译的事实仅表明 GCC 4.1.2 中的一个错误——代码本质上仍然不正确。
不幸的是,我暂时想不出好的解决方法。以下编译但将您限制为只有两个模板参数的容器(其中第二个是分配器),这可能不是您最终想要的:
#include <iostream>
#include <string>
#include <vector>
#include <boost/assign/list_of.hpp>
template<
template<typename, typename> class containerType,
typename allocatorType,
typename elemType
>
containerType<elemType, allocatorType >
to(boost::assign_detail::generic_list<elemType> const& list)
{
return list; // no need to explicitly construct a containerType instance
}
template<template<typename, typename> class containerType, typename elemType>
containerType<elemType, std::allocator<elemType> >
to(boost::assign_detail::generic_list<elemType> const& list)
{
return to<containerType, std::allocator<elemType> >(list);
}
static std::vector<std::vector<std::string> > names = boost::assign::list_of
(to<std::vector>(boost::assign::list_of<std::string>("A")("B")("C")))
(to<std::vector>(boost::assign::list_of<std::string>("D")("E")("F")));
int main()
{
typedef std::vector<std::vector<std::string> >::const_iterator outer_iter_t;
typedef std::vector<std::string>::const_iterator inner_iter_t;
for (outer_iter_t itVec = names.begin(); itVec != names.end(); ++itVec)
for (inner_iter_t itStr = itVec->begin(); itStr != itVec->end(); ++itStr)
std::cout << "Value is " << *itStr << '\n';
}
编辑(响应 dribeas 的评论):已更新以允许调用者覆盖默认分配器。
关于C++ 编译器错误(试图创建 vector 的静态 vector ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7179974/