模板函数参数的 C++17 invoke_result 和 static_assert

C++17 invoke_result and static_assert for template func param

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

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

#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;
}

您在

上有一个额外的 ()
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;

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

最终代码应该是

#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 Whosebug, 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;
}

这并非在所有功能情况下都有效,但对于函数指针,应该有效。

如果你定义自定义模板如下

template <typename>
struct baz;

template <typename R, typename ... Args>
struct baz<R(*)(Args...)>
 { using retType = R; };

你的例子变成了

template <typename T, typename Func>
void Example(Func func)
 {
   static_assert(std::is_same<typename baz<Func>::retType,
                              std::unique_ptr<T>>::value,  "!");
 }

下面是一个完整的编译示例

#include <type_traits>
#include <memory>

template <typename>
struct baz;

template <typename R, typename ... Args>
struct baz<R(*)(Args...)>
 { using retType = R; };

template <typename T, typename Func>
void Example(Func func)
 {
   static_assert(std::is_same<typename baz<Func>::retType,
                              std::unique_ptr<T>>::value,  "!");
 }

struct Foo
 {
   Foo (int i) : My_I{i}
    { }

   Foo () : My_I{99}
    { }

   ~Foo() = default;

   int My_I;
 };

std::unique_ptr<Foo> bar0 ()
{ return std::make_unique<Foo>(11); }

std::unique_ptr<Foo> bar1 (int)
{ return std::make_unique<Foo>(11); }

std::unique_ptr<Foo> bar2 (int, long)
{ return std::make_unique<Foo>(11); }

int main ()
 {
   Example<Foo>(&bar0);
   Example<Foo>(&bar1);
   Example<Foo>(&bar2);
 }

不幸的是,此解决方案仅适用于函数指针,不适用于(通过示例)lambda 函数(当不能转换为函数指针时)或 类 与 operator()

如果您可以使用 C++17——我想是您的情况,如果您使用 std::invoke_result——您也可以使用 std::function 的自动推导指南。

因此,在 C++17 中,您可以忘记 baz 结构并简单地编写

template <typename T, typename Func>
void Example(Func func)
 {        
   static_assert(std::is_same<
       typename decltype(std::function{func})::result_type,
       std::unique_ptr<T>>::value,  "!");
 }

或者,在您的 Register() 方法中

template<typename My_Type, typename Func>
static bool Register(Func func)
{
    static_assert(std::is_same<
       typename decltype(std::function{func})::result_type,
       std::unique_ptr<My_Type>>::value,  "!");

    bool isRegistered = false;

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

    return isRegistered;
}