How can I determine the return type of a C++11 member function

后端 未结 4 1147
心在旅途
心在旅途 2021-02-19 20:39

I am trying to determine the return type of a various C++ member functions. I understand that decltype and std::declval can be used to do this, but I am having problems with the

4条回答
  •  后悔当初
    2021-02-19 21:08

    Latest syntax to deduce return type at compile time is like this:

    std::invoke_result_t someVariable;
    

    Let's consider an example, that you want to construct an object with a default value, eg. QVector(), but you need to deduce this type from template parameter, in our example is template parameter Presenter and we need to deduce return type for a class method with one parameter Presenter::present(QSqlQuery &):

    template
    inline auto defaultReturnValue() const
    {
        return std::invoke_result_t();
    }
    

    The above code deduces the return type for this class:

    class VectorPresenter final
    {
    public:
        QVector present(QSqlQuery &query) const;
    };
    

    Finally, you will call:

    const auto defaultValue = defaultReturnValue();
    

    The result will be that you will have QVector instance in defaultValue variable. And now, you can create a presenter class, which will return any type and you will be able to return the default value for this type.

提交回复
热议问题