具有void返回类型和模板化参数的std :: function

pek*_*u33 4 c++ templates

我有一个

template<class R>
class MyClass
{
    public:
        typedef std::function<void (const R)> ...;
};
Run Code Online (Sandbox Code Playgroud)

在我尝试使用MyClass <void>之前一切正常.

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

typedef std::function<void (void)> ...;
Run Code Online (Sandbox Code Playgroud)

而且不想合作.

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

typedef std::function<void ()> ...;
Run Code Online (Sandbox Code Playgroud)

由于类非常大,我更喜欢type_traits和enable_if-like,而不是为void创建特化.

Jar*_*d42 6

如评论中所述,您可以使用帮助程序类:

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

template <>
struct MyClassHelper<void>
{
    using function_type = std::function<void ()>;
};
Run Code Online (Sandbox Code Playgroud)

然后,在 MyClass

template<class R>
class MyClass
{
public:
    using function_type = typename MyClassHelper<R>::function_type;
};
Run Code Online (Sandbox Code Playgroud)