Using template for return value. how to handle void return?

后端 未结 2 1943
無奈伤痛
無奈伤痛 2021-02-05 07:46

I have structure for storing callback function like this:

template
struct CommandGlobal : CommandBase
{
    typedef boost::function Co         


        
相关标签:
2条回答
  • 2021-02-05 08:15

    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) 
            return comm();
        else
            return static_cast<T>(NULL);
    }
    

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


    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!")
    }
    

    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
    }
    

    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.

    0 讨论(0)
  • 2021-02-05 08:20

    If it's just the return statement, this should do the trick:

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

    If there's more to it, specialize the template for void.

    0 讨论(0)
提交回复
热议问题