【问题标题】:How to make std::function<void(Arg)> compile, when typename Arg = void? [duplicate]当 typename Arg = void 时,如何使 std::function<void(Arg)> 编译? [复制]
【发布时间】:2018-07-25 07:27:26
【问题描述】:

假设我有一个这样的类型别名:

template <typename Arg>
using Func = std::function<void(Arg)>;

除了 Arg 为 void 的情况外,它工作正常:

Func<int> f1;
Func<void> f2; // doesn't compile

第二个给出如下编译错误:

error: invalid parameter type ‘void’using Func = std::function<void(Arg)>;
error: in declaration ‘using Func = class std::function<void(Arg)>’

如何才能为std::function&lt;void()&gt; 创建别名?

【问题讨论】:

    标签: c++11 gcc


    【解决方案1】:

    您可以尝试添加一些模板特化:

    template<typename T>
    struct FuncImpl
    {
        using type = std::function<void(T)>;
    };
    
    template<>
    struct FuncImpl<void>
    {
        using type = std::function<void()>;
    };
    
    template <typename Arg>
    using Func = typename FuncImpl<Arg>::type;
    

    EXAMPLE

    【讨论】:

    • 谢谢!它可以解决问题(答案已接受),但有解释吗?
    • @AlexandreA。嗯,我刚刚做了一些搜索,似乎问题出在:stackoverflow.com/questions/13372173/…。不幸的是,我在发布答案后检查了它:(
    • 确实,但无论如何感谢您指出正确的方向!
    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 2014-12-11
    • 2013-07-15
    • 2023-02-07
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多