使用模板作为返回值。如何处理void return? [英] Using template for return value. how to handle void return?

查看:536
本文介绍了使用模板作为返回值。如何处理void return?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样存储回调函数的结构:

I have structure for storing callback function like this:

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

    virtual T Execute() const
    {
        if(comm)
            return comm();
        return NULL;
    }
};

似乎它应该工作正常,除非T是void,因为Execute函数要返回一个值。 。

Seems like it should work fine except when T is void because the Execute function wants to return a value..

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

What is the best solution to this problem?

谢谢!

推荐答案

此回答基于 this fun-fact :在返回 void 的函数中,可以返回任何类型为void的表达式。

This answer is based off this fun-fact: In a function returning void, you can return any expression of which the type is void.

所以简单的解决方案是:

So the simple solution is:

virtual T Execute() const
{
    if (comm) // boolean logic change, typo in OP?
        return comm();
    else
        return static_cast<T>(NULL);
}

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

When T = void, the last return statement is equivalent to return;.

但是,我觉得这是坏的设计。 NULL 对于 T 有意义吗?我不这么认为。我会抛出异常:

However, I feel this is bad design. Is NULL meaningful for every T? I don't think so. I would throw an exception:

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

但是,这是通过自动完成的Boost ,因此您的代码变得更干净:

However, this is done automatically by Boost, so your code becomes the much cleaner:

virtual T Execute() const
{
    return comm();
}

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

You could then add additional functionality, such as:

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

因此,用户可以检查它是否可以在调用它之前调用。当然,在这一点上,除非你的类有额外的功能,你为了这个问题的原因,我没有看到没有理由不使用 boost :: function 第一名。

So the user can check if it can be called prior to calling it. Of course at this point, unless your class has additional functionality you've left out for the sake of the question, I see no reason not to just use boost::function in the first place.

这篇关于使用模板作为返回值。如何处理void return?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆