Variadic templated class - 0 长度包构造函数冲突

Variadic templated class - 0 length package constructor collision

给出

template<class... Args>
struct foo {

    function<void(Args...)>     m_function;
    unique_ptr<tuple<Args...>>  m_args;

    foo(const std::function<void(Args...)>& func, Args... args) :
        m_function{ func }, m_args{ new tuple<Args...>(args...) } {

        cout << "ctor 1" << endl;
    }

    // <some template wizardry here>
    foo(const std::function<void(Args...)>& func) :
        m_function{ func } {

        cout << "ctor 2" << endl;
    }
};

我希望 ctor2 仅在 sizeof...(Args) != 0 时被实例化(否则我会发生冲突..)。

这里似乎可行(没有冲突)

template<Args...>
foo(const std::function<void(Args...)>& func) :
    m_function{ func } {

    cout << "ctor 2" << endl;
}

但我不知道how/why或者它是否可靠。

我也可能会使用类似

的东西
std::enable_if<sizeof...(Args) != 0, ???>

如何使用 std::enable_if 解决此问题以及我的第二个代码示例中发生了什么?

struct foo {
    using Func = std::function<void(Args...)>;
    foo(const Func& func, Args... args)  { ... }

    struct none {};
    using A = typename std::conditional<sizeof...(Args) > 0, Func, none>::type;

    foo(const A& func) { ... };

正如 Johannes Schaub - litb 在评论中所指出的,您可以简单地添加一个未使用的模板参数的可变列表,只是为了转换模板中的第二个构造函数并优先(避免冲突)第一个那不是模板构造函数。

所以你可以简单地写

template <typename ...>
foo (std::function<void(Args...)> const & func)
    : m_function{ func }
 { std::cout << "ctor 2" << std::endl; }

但为了满足您的要求

I would like ctor2 to be instantiated only when sizeof...(Args) != 0

你可以试试(不太优雅,但也许更容易理解)

template <bool B = (sizeof...(Args) > 0u),
          std::enable_if_t<B, bool> = true>
foo (std::function<void(Args...)> const & func)
    : m_function{ func }
 { std::cout << "ctor 2" << std::endl; }