std::函数,返回类型为void,参数为模板化

std::function with void return type and templated parameter

本文关键字:参数 void 返回类型 std 函数      更新时间:2023-10-16

我有一个

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

在我尝试使用MyClass<void>。

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

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

并且不想合作。

如果void被用作R参数,我希望typedef的行为像:

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

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

如注释中所述,您可以使用一个助手类:

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