当作为参数传递给函数时,是否可以在表达式的内容被捕获之前捕获它?

Fie*_*lds 0 c++

假设我有一个简单的函数,它接受一个条件,然后返回一些东西.

例如:

bool is_even(int num){
   return (num % 2 == 0);
}
void Foo(conditional)
{
    if(conditional)
        std::cout << "Bar" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

是否有可能在函数计算之前将参数或表达式作为整体进入条件?

所以我的意思是,如果条件是is_even(2),我可以在评估之前获得表达式"is_even(2)",而不是真值(True)吗?

Bat*_*eba 6

一种方法是使用一个将()运算符重载到的类bool:

struct Bar
{
     bool operator()() const;
};
Run Code Online (Sandbox Code Playgroud)

和写

template <typename Y>
void Foo(const Y& y)
{
    if(y()){
        std::cout << "Bar" << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将任何状态封装到Bar.如果您不喜欢需要y()在评估点编写的事实,可以通过定义转换运算符来进一步调整语法bool:

struct Bar
{
    operator bool() const;
};
Run Code Online (Sandbox Code Playgroud)

和写

template <typename Y>
void Foo(const Y& y)
{
    if (y){
        std::cout << "Bar" << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这样做的过程中,你绊倒了演员,以及那个奇妙的C++工程Boost Spirit的基础.请参阅https://en.wikipedia.org/wiki/Actor_modelhttps://theboostcpplibraries.com/boost.spirit