【问题标题】:std::function with void return type and templated parameter具有 void 返回类型和模板化参数的 std::function
【发布时间】:2015-12-27 17:51:07
【问题描述】:

我有一个

template<class R>
class MyClass
{
    public:
        typedef std::function<void (const R)> ...;
};

在我尝试使用 MyClass 之前一切正常。

在这种情况下,编译器将 typedef 扩展为

typedef std::function<void (void)> ...;

不想合作。

如果将 void 用作 R 参数,我希望 typedef 的行为类似于:

typedef std::function<void ()> ...;

由于这个类相当大,我更喜欢 type_traits 和 enable_if 之类的东西,而不是为 void 创建专门化。

【问题讨论】:

  • 类似于 make_const&lt;R&gt;::type 的东西,专门针对 void?
  • 规则在 C++11,IIRC 左右发生了变化。我的直觉是现在应该编译。但是与观察到的现实不匹配表明这是您最好避免的语言的晦涩的极端情况(例如,难以维护代码!),例如通过对麻烦案例的明确专业化。
  • 或者,template&lt;class... Params&gt; class MyClass{ using type = std::function&lt;void(const Params...)&gt;; }; - 当您不需要任何参数时,您可以简单地将参数列表留空。
  • 也许像typename conditional&lt;is_void&lt;R&gt;::value, void(), void(typename conditional&lt;is_void&lt;R&gt;::value, int, R&gt;::type)&gt;::type 这样的脏东西。还要注意void(R)void(const R) 是等价的,是同一个类型。
  • @JohannesSchaub-litb 除了 R 是数组类型的极端情况:)

标签: c++ templates


【解决方案1】:

正如评论中提到的,您可以使用辅助类:

template<class R>
struct MyClassHelper
{
    using function_type = std::function<void (const R)>;
};

template <>
struct MyClassHelper<void>
{
    using function_type = std::function<void ()>;
};

然后,在MyClass

template<class R>
class MyClass
{
public:
    using function_type = typename MyClassHelper<R>::function_type;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 2020-11-26
    • 2021-05-21
    相关资源
    最近更新 更多