我想为lexical_cast
类型扩展vector<uint>
方法,但它不起作用。
我尝试了以下代码:
#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;
}
}
我收到了以下错误:
错误:'std :: string的template-id'lexical_cast' boost :: lexical_cast(std :: vector)'与any不匹配 模板声明
答案 0 :(得分:3)
可以通过重载operator<<
来扩展词法转换。
问题是std::vector
和uint
是您的类型:它们是内置的或标准库。这使得你无法在命名空间内重载或专门化。
真正的解决方案:
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
现在神奇地工作了!
<强> Live On Coliru 强>
#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
使用自定义IO操纵器,例如: How do I output a set used as key for a map?
#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}; }
这些也适用于Boost Lexicalcast:
<强> Live On Coliru 强>
#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