大佬教程收集整理的这篇文章主要介绍了c只要写入流就执行函数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <streambuf> #include <ostream> #include <functional> #include <String> #include <memory> #include <iostream> // only for tesTing... #if HAS_FUNCTION typedef std::function<void(std::string)> function_type; #else class function_type { private: struct base { virtual ~base() {} virtual base* clone() const = 0; virtual void call(std::string const&) = 0; }; template <typename Function> struct concrete : base { Function d_function; concrete(Function function) : d_function(function) { } base* clone() const { return new concrete<Function>(this->d_function); } void call(std::string const& value) { this->d_function(value); } }; std::auto_ptr<base> d_function; public: template <typename Function> function_type(Function function) : d_function(new concrete<Function>(function)) { } function_type(function_type const& other) : d_function(other.d_function->clone()) { } function_type& operator= (function_type other) { this->swap(other); return *this; } ~function_type() {} void swap(function_type& other) { std::swap(this->d_function,other.d_function); } void operator()(std::string const& value) { this->d_function->call(value); } }; #endif class functionbuf : public std::streambuf { private: typedef std::streambuf::Traits_type Traits_type; function_type d_function; char d_buffer[1024]; int overflow(int C) { if (!Traits_type::eq_int_type(c,Traits_type::eof())) { *this->pptr() = Traits_type::TO_CHAR_type(c); this->pbump(1); } return this->sync()? Traits_type::not_eof(C): Traits_type::eof(); } int sync() { if (this->pbase() != this->pptr()) { this->d_function(std::string(this->pbase(),this->pptr())); this->setp(this->pbase(),this->epptr()); } return 0; } public: functionbuf(function_type const& function) : d_function(function) { this->setp(this->d_buffer,this->d_buffer + sizeof(this->d_buffer) - 1); } }; class ofunctionstream : private virtual functionbuf,public std::ostream { public: ofunctionstream(function_type const& function) : functionbuf(function),std::ostream(static_cast<std::streambuf*>(this)) { this->flags(std::ios_base::unitbuf); } }; void some_function(std::string const& value) { std::cout << "some_function(" << value << ")\n"; } int main() { ofunctionstream out(&some_function); out << "Hello" << ',' << " world: " << 42 << "\n"; out << std::nounitbuf << "not" << " as " << "many" << " calls\n" << std::flush; }
上面代码的一大部分实际上与手头的任务无关:它实现了std :: function< void(std :: String)>的原始版本.如果C 2011无法使用.
如果你不想要那么多的调用,你可以关闭std :: ios_base :: unitbuf并仅在刷新流时发送数据,例如使用std :: flush(是的,我知道std :: endl但不幸的是它通常被误用,我强烈建议摆脱它并使用std :: flush,其中一个flush是真的意思).
以上是大佬教程为你收集整理的c只要写入流就执行函数全部内容,希望文章能够帮你解决c只要写入流就执行函数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。