C++ 模板专门化(boost::词法转换)
我想为C++ 模板专门化(boost::词法转换),c++,templates,boost,template-specialization,C++,Templates,Boost,Template Specialization,我想为vector类型扩展lexical\u cast方法,但它不起作用。 我尝试了以下代码: #include <boost/lexical_cast.hpp> namespace boost { template <> inline string lexical_cast <string>(vector<uint> source) { string tmp; for (size_t i
vector
类型扩展lexical\u cast
方法,但它不起作用。
我尝试了以下代码:
#include <boost/lexical_cast.hpp>
namespace boost
{
template <>
inline string lexical_cast <string>(vector<uint> source)
{
string tmp;
for (size_t i = 0; i < source.size(); ++i)
if (i < source.size() - 1)
tmp += boost::lexical_cast<string>(source[i]) + "|";
else
tmp += boost::lexical_cast<string>(source[i]);
return tmp;
}
}
#包括
名称空间提升
{
模板
内联字符串词法转换(向量源)
{
串tmp;
对于(size_t i=0;i
我得到了以下错误:
错误:“std::string”的模板id“lexical\u cast”
boost::lexical_cast(std::vector)“”与任何
模板声明
词法强制转换可以通过重载
运算符或添加操纵器方法来扩展,您不能更改正在专门化的函数模板的原型,而是通过常量&
获取其参数。如果将参数类型更改为vector const&
,代码将编译。但是使用下面答案中描述的另一种方法,专门化函数模板通常不是一个好主意,请参阅
#include <vector>
#include <ostream>
struct Source {
std::vector<uint> _data;
friend std::ostream& operator<<(std::ostream& os, Source const& s) {
bool first = true;
for(auto i : s._data) {
if (!first) os << "|";
first = false;
os << i;
}
return os;
}
};
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <iomanip> // for std::quoted
int main() {
Source s { {1,2,3,4,5} };
std::cout << "Source is " << s << "\n";
std::string text = boost::lexical_cast<std::string>(s);
std::cout << "Length of " << std::quoted(text) << " is " << text.length() << "\n";
}
Source is 1|2|3|4|5
Length of "1|2|3|4|5" is 9
#include <ostream>
template <typename Container>
struct pipe_manip {
Container const& _data;
friend std::ostream& operator<<(std::ostream& os, pipe_manip const& manip) {
bool first = true;
for(auto& i : manip._data) {
if (!first) os << "|";
first = false;
os << i;
}
return os;
}
};
template <typename Container>
pipe_manip<Container> as_pipe(Container const& c) { return {c}; }
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <set>
#include <vector>
int main() {
std::vector<uint> s { {1,2,3,4,5} };
std::cout << "Source is " << as_pipe(s) << "\n";
std::string text = boost::lexical_cast<std::string>(as_pipe(std::set<std::string>{"foo", "bar", "qux"}));
std::cout << "Other containers work too: " << text << "\n";
}
Source is 1|2|3|4|5
Other containers work too: bar|foo|qux