模板专业化(boost :: lexical_cast) [英] Template specialization (boost::lexical_cast)
问题描述
我想将lexical_cast
方法扩展为vector<uint>
类型,但是不起作用.
我尝试了以下代码:
I want to extend the lexical_cast
method for vector<uint>
types, but it's not working.
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;
}
}
我遇到以下错误:
错误:"std :: string"的模板ID"lexical_cast" boost :: lexical_cast(std :: vector)’与任何内容都不匹配 模板声明
error: template-id ‘lexical_cast’ for ‘std::string boost::lexical_cast(std::vector)’ does not match any template declaration
推荐答案
可以通过重载operator<<
来扩展词法转换.
Lexical cast can be extended by overloading operator<<
.
问题是std::vector
和uint
是您的类型:它们是内置库或标准库.这使您无法在名称空间内进行重载或专门化.
Problem is that std::vector
nor uint
are your types: they're builtin or standard library. This makes it not-okay for you to overload or specialize inside the namespace.
真正的解决方案:
C ++支持强类型输入:
C++ is favors strong typing:
#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;
}
};
奖励
lexical_cast
现在可以正常运行了!
BONUS
lexical_cast
now magically works!
#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
使用自定义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}; }
这些也可以与Boost Lexicalcast一起使用:
These also work with 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";
}
打印
Source is 1|2|3|4|5
Other containers work too: bar|foo|qux
这篇关于模板专业化(boost :: lexical_cast)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!