使用构造函数中的可变参数初始化std :: tuple

问题描述 投票:0回答:1

我有一个创建std::function的类。为了简单起见,在此示例中,我将说std::function返回一个布尔值。 std::function需要接收一个可变参数元组。目前,我有

template<class... FuncArgs>
class Function
{
public:
    // Type that std::function returns
    using func_ret_ty = bool;

private:
    std::function<func_ret_ty(std::tuple<FuncArgs...>)> m_Function;
    std::tuple<FuncArgs...> m_Args;  // Stores m_Function's arguments

public:
    Function(
        std::function<func_ret_ty(std::tuple<FuncArgs...>)> function,
        FuncArgs... args)
        : m_Function(function)
        , m_Args(std::make_tuple(std::forward<FuncArgs>(args)...))
    {}
};

我的问题很简单:这行得通吗?

[更具体地说,我很担心,因为在声明function的类型时似乎存在循环依赖关系。实现的另一个想法是:

template<class FuncTy, class FuncArgs...>
class Function
{
public:
    using func_ret_ty = bool;

private:
    FuncTy m_Function;
    std::tuple<FuncArgs...> m_Args;

public:
    Function(
        FuncTy function,
        FuncArgs... args)
        : m_Args(std::make_tuple(std::forward<FuncArgs>(args)...))
    {
        static_assert(
            std::is_same_v<FuncTy, std::function<func_ret_ty(std::tuple<FuncArgs...>)>>,
            "FuncTy invalid type!"
        );

        m_Function = std::move(function);
    }
};

第二种实现更好吗?有没有更好的方法可以做到这一点?

c++ templates types variadic-templates sfinae
1个回答
0
投票

第一个实现对我来说看起来更好,因为您不必通过两次提供函数参数来重复自己。因为您将返回类型设置为bool,所以我建议将类的名称更改为Predicate,这是一个众所周知的术语,用于描述返回布尔值的函数。

请注意,std::function也可以将参数包作为模板参数,因此您也可以这样做:

std::function<func_ret_ty(FuncArgs...)> m_Function;
© www.soinside.com 2019 - 2024. All rights reserved.