【问题标题】:Null implementation of type boost::functionsboost::functions 类型的空实现
【发布时间】:2013-10-09 09:23:02
【问题描述】:

我有这样的事情:

boost::function<void(void)> redStyle = boost::bind(colorStyle, "red");

boost::function<void(void)> blueBlinkingStyle = boost::bind(animatedStyle, "blue", BLINKING);

这是定义 nullStyler 的正确方法吗:

void nothing(){}
boost::function<void(void)> noStyle = boost::bind(nothing);

我在想我可以这样做,但是会抛出空函数:

boost::function<void(void)> noStyle;

使用 styler 函数的代码可以检查空,而不是使用“空对象模式”。哪个更好?在我的 Detail 命名空间中有一个奇怪的空函数或检查是否为空?

【问题讨论】:

    标签: c++ c++98 null-object-pattern


    【解决方案1】:

    我希望有一个无操作功能。它使意图清晰,并且使您免于检查函子是否为空(假设您不必出于其他原因进行检查)。

    请注意,您不需要调用 bind。你可以这样做:

    boost::function<void(void)> noStyle = nothing;
    

    例子:

    #include <boost/function.hpp>
    #include <iostream>
    
    void hello()
    {
      std::cout << "hello" << std::endl;
    }
    
    int main()
    {
      boost::function<void(void)> f = hello;
      f();
    }
    

    【讨论】:

    • 或者。 std::function&lt;void(void)&gt; noStyle = []{}; ... 这要求您少输入 3 个字符。
    • @Nawaz 好点,虽然我总是假设一个人在不支持 C++11 时使用boost::function
    • @Angew 我显然把整个“C++11 是 C++”的事情说得太远了:)
    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 2022-01-12
    • 2010-11-23
    • 2012-11-24
    • 2020-06-11
    • 1970-01-01
    • 2011-01-31
    • 2012-11-01
    相关资源
    最近更新 更多