使用模板返回值.如何处理无效返回?

Seb*_*rds 19 c++ templates callback

我有用于存储回调函数的结构,如下所示:

template<class T>
struct CommandGlobal : CommandBase
{
    typedef boost::function<T ()> Command;
    Command comm;

    virtual T Execute() const
    {
        if(comm)
            return comm();
        return NULL;
    }
};
Run Code Online (Sandbox Code Playgroud)

看起来它应该工作正常,除非T是无效的,因为Execute函数想要返回一个值..

这个问题的最佳解决方案是什么?

谢谢!

GMa*_*ckG 13

这个答案基于这个有趣的事实:在函数返回中void,您可以返回任何类型为void的表达式.

所以简单的解决方案是:

virtual T Execute() const
{
    if (comm) 
        return comm();
    else
        return static_cast<T>(NULL);
}
Run Code Online (Sandbox Code Playgroud)

何时T = void,最后一个return语句相当于return;.


但是,我觉得这是糟糕的设计.是NULL有意义的每一个 T?我不这么认为.我会抛出一个例外:

virtual T Execute() const
{
    if (comm)
        return comm();
    else
        throw std::runtime_error("No function!")
}
Run Code Online (Sandbox Code Playgroud)

但是,这是由Boost自动完成,因此您的代码变得更加清晰:

virtual T Execute() const
{
    return comm();
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以添加其他功能,例如:

bool empty(void) const
{
    return !comm; // or return comm.empty() if you're the explicit type
}
Run Code Online (Sandbox Code Playgroud)

因此,用户可以在调用之前检查是否可以调用它.当然,在这一点上,除非你的课程有额外的功能你为了这个问题而遗漏了,我认为没有理由不首先使用boost::function.

  • 那是我在那看到的C风格演员吗? (2认同)