[英]C++ enhanced cat
Suppose I have a function from string to string, such as for example: 假设我有一个从字符串到字符串的函数,例如:
string identity(string text) {
return text;
}
How can I print the function applied to input to output, avoiding explicit variables, input and output handling? 如何打印应用于输入到输出的函数,避免显式变量,输入和输出处理? Something like interact
in Haskell. 在Haskell中可能会发生interact
。
int main() {
std::interact(identity);
}
This would really cut down obvious code, and let the algoritmh and the logic stand out instead. 这确实会减少明显的代码,而让算法和逻辑脱颖而出。
Example usage would be: 用法示例为:
$./enhanced_cat
Example
Example
$
template<class F>
struct interacter_t {
F f;
void operator()( std::istream& is = std::cin, std::ostream& os = std::cout ) {
std::string in;
while( getline( is, in ) ) {
os << f(std::move(in)) << '\n';
}
}
};
template<class F>
interacter_t<std::decay_t<F>> interact( F&& f ) {
return {std::forward<F>(f)};
}
then: 然后:
int main() {
auto io = interact(identity);
std::cout << "Start:\n";
io();
std::cout << "End.\n";
}
I added the separate invocation to creation of the interactor object. 我在交互器对象的创建中添加了单独的调用。
You can do it on one line: 您可以一行完成:
std::cout << "Start:\n";
interact(identity)();
std::cout << "End.\n";
or you can modify interact
to run the interactor_t
instead of returning it. 或者您可以修改interact
来运行interactor_t
而不是返回它。 I personally like that distinction: creation and execution are different things. 我个人喜欢这种区别:创建和执行是不同的东西。
live example . 现场例子 。
This version reads everything from the input stream until it ends. 此版本从输入流读取所有内容,直到结束。 Reading less than that is easy, just replace the body of operator()
. 读取不到的内容很容易,只需替换operator()
的主体即可。
You could roll your own interact, something like the below. 您可以滚动自己的交互,如下所示。 (Note: probably won't actually compile as is.) (注意:可能实际上不会按原样编译。)
void interact(string (*function)(string))
{
string input;
getline(cin, input);
cout << function(input) << endl;
}
You can easily write such a thing yourself using std::function
. 您可以使用std::function
轻松编写此类内容。 Example: 例:
#include <string>
#include <iostream>
#include <functional>
std::string identity(std::string const& text) {
return text;
}
void interact(std::function<std::string(std::string const&)> f)
{
std::string input;
std::getline(std::cin, input);
std::cout << f(input);
}
int main()
{
interact(identity);
}
But that certainly doesn't look like idiomatic C++. 但这肯定不像惯用的C ++。 Even though C++ supports functional programming to a certain extent, it's not a functional programming language, and you should not try to write Haskell in C++. 即使C ++在某种程度上支持函数式编程,它也不是函数式编程语言,并且您不应该尝试用C ++编写Haskell。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.