如果你查看boost::signals
库,你会看到一个非常漂亮的例子,非常优雅:
假设你有 4 个函数,比如:
void print_sum(float x, float y)
{
std::cout << "The sum is " << x+y << std::endl;
}
void print_product(float x, float y)
{
std::cout << "The product is " << x*y << std::endl;
}
void print_difference(float x, float y)
{
std::cout << "The difference is " << x-y << std::endl;
}
void print_quotient(float x, float y)
{
std::cout << "The quotient is " << x/y << std::endl;
}
然后,如果您想以优雅的方式调用它们,请尝试:
boost::signal<void (float, float)> sig;
sig.connect(&print_sum);
sig.connect(&print_product);
sig.connect(&print_difference);
sig.connect(&print_quotient);
sig(5, 3);
输出是:
The sum is 8
The product is 15
The difference is 2
The quotient is 1.66667