[英]Template specialization (boost::lexical_cast)
I want to extend the lexical_cast
method for vector<uint>
types, but it's not working. 我想扩展
vector<uint>
类型的lexical_cast
方法,但它不起作用。 I tried the following code: 我尝试了以下代码:
#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;
}
}
I got following error: 我收到以下错误:
error: template-id 'lexical_cast' for 'std::string boost::lexical_cast(std::vector)' does not match any template declaration
错误:'std :: string boost :: lexical_cast(std :: vector)'的template-id'lexical_cast'与任何模板声明都不匹配
Lexical cast can be extended by overloading operator<<
. 可以通过重载
operator<<
来扩展词法转换。
Problem is that std::vector
nor uint
are your types: they're builtin or standard library. 问题是
std::vector
和uint
是你的类型:它们是内置的或标准的库。 This makes it not-okay for you to overload or specialize inside the namespace. 这使您无法在命名空间内重载或专门化。
Real solution: 真正解决方案
C++ is favors strong typing: C ++有利于强类型:
#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;
}
};
BONUS
lexical_cast
now magically works!奖励
lexical_cast
现在神奇地工作!
#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";
}
Prints 打印
Source is 1|2|3|4|5
Length of "1|2|3|4|5" is 9
Use a custom IO Manipulator like eg How do I output a set used as key for a map? 使用自定义IO操纵器,例如如何输出用作地图键的集合?
#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}; }
These also work with Boost Lexicalcast: 这些也适用于Boost Lexicalcast:
#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";
}
Prints 打印
Source is 1|2|3|4|5
Other containers work too: bar|foo|qux
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.