gpt4 book ai didi

c++ - 模板特化 (boost::lexical_cast)

转载 作者:行者123 更新时间:2023-11-30 02:21:51 26 4
gpt4 key购买 nike

我想扩展 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;
}
}

出现以下错误:

error: template-id ‘lexical_cast’ for ‘std::string boost::lexical_cast(std::vector)’ does not match any template declaration

最佳答案

可以通过重载来扩展词法转换 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 now magically works!

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

使用自定义 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

关于c++ - 模板特化 (boost::lexical_cast),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47882043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com