首页 > 解决方案 > 模板函数参数的 C++17 调用结果和静态断言

问题描述

这纯粹是为了在进行泛型编程时获得更多知识。如何确保作为模板参数传入另一个函数的函数的返回类型,该函数可以采用不同数量的参数(0 到 N)。

编辑:我正在尝试使用std::invoke_resultstatic_assert()确保注册工厂方法的正确返回类型。我使用了一个比第一个发布的更好的例子来提供更多的清晰度。

#include <string>
#include <memory>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>

using namespace std;

class Factory final
{
public:
    template<typename My_Type, typename Func>
    static bool Register(Func func)
    {
        // issue is these two lines of code, when trying to register Derived1 and Derived2 create functions
        typename invoke_result<Func>::type result;
        static_assert(is_same<decltype(result), unique_ptr<My_Type>>::value, "Not a unique pointer to type 'My_Type'");

        bool isRegistered = false;

        if (GetCreateFunctions().end() == GetCreateFunctions().find(typeid(My_Type)))
        {
            GetCreateFunctions()[typeid(My_Type)] = reinterpret_cast<void*>(func);
            isRegistered = true;
        }

        return isRegistered;
    }

    template<typename My_Type, typename... Args>
    static unique_ptr<My_Type> Create(Args&&... args)
    {
        unique_ptr<My_Type> type = nullptr;
        auto iter = GetCreateFunctions().find(typeid(My_Type));

        if (GetCreateFunctions().end() != iter)
        {
            typedef unique_ptr<My_Type>(*create_func)(Args&&...);
            auto create = reinterpret_cast<create_func>(iter->second);
            type = create(forward<Args>(args)...);
        }

        return type;
    }

private:
    static unordered_map<type_index, void*>& GetCreateFunctions()
    {
        static unordered_map<type_index, void*> map;
        return map;
    }
};

class Base
{
public:
    Base(unique_ptr<string>&& moveString)
        :
        _moveString(move(moveString))
    {
    }

    virtual ~Base() = default;
    virtual void DoSomething() const = 0;

protected:
    unique_ptr<string> _moveString;
};

class Derived1 final : public Base
{
public:
    Derived1(unique_ptr<string>&& moveString)
        :
        Base(move(moveString))
    {
    }

    ~Derived1() = default;

    void DoSomething() const override
    {
        if (_moveString)
        {
            // do something...
        }
    }

private:
    static const bool _isRegistered;

    static unique_ptr<Derived1> Create(unique_ptr<string>&& moveString)
    {
        return make_unique<Derived1>(move(moveString));
    }
};

const bool Derived1::_isRegistered = Factory::template Register<Derived1>(&Derived1::Create);

class Derived2 final : public Base
{
public:
    Derived2()
        :
        Base(make_unique<string>("Default"))
    {
    }

    ~Derived2() = default;

    void DoSomething() const override
    {
        if (_moveString)
        {
            // do something...
        }
    }

private:
    static const bool _isRegistered;

    static unique_ptr<Derived2> Create()
    {
        return make_unique<Derived2>();
    }
};

const bool Derived2::_isRegistered = Factory::template Register<Derived2>(&Derived2::Create);


int main(int argc, char** argv)
{
    string moveString = "moveString";
    unique_ptr<Base> myBase_Derived1 = Factory::template Create<Derived1>(make_unique<string>(move(moveString)));
    unique_ptr<Base> myBase_Derived2 = Factory::template Create<Derived2>();

    if (myBase_Derived1)
        printf("Success\n");

    if (myBase_Derived2)
        printf("Success\n");

    return 0;
}

标签: c++templatesvariadic-templatesc++17static-assert

解决方案


你有一个额外()

static_assert(std::is_same<decltype(result), std::unique_ptr<T>/* here */ >::value, "Not a unique pointer to type 'T'");

typename std::invoke_result<Func/* here */>::type result;

A并且A()是两种不同的类型。A()是一个返回 aA且不带参数的函数。

最终代码应该是

#include <type_traits>
#include <memory>

using namespace std;

template<typename T, typename Func>
void Example(Func)
{
    // func can have params, or have no params
    typename std::invoke_result<Func>::type result;
    static_assert(std::is_same<decltype(result), std::unique_ptr<T> >::value, "Not a unique pointer to type 'T'"); // can't get this correct (tried different variations, looked over stackoverflow, etc.)
}

class Foo
{
public:
    Foo(int i)
        : My_I(i)
    {
    }

    Foo()
        : My_I(99)
    {
    }

    ~Foo() = default;

    int My_I;
};

unique_ptr<Foo> CreateWithInt()
{
    return make_unique<Foo>(11);
}

int main()
{
    Example<Foo>(&CreateWithInt);
    return 0;
}

推荐阅读