繁体   English   中英

可变参数模板类-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;
    }
};

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

此权限似乎正常工作(无冲突)

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

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

但我不知道如何/为什么或是否可靠。

我也可能使用Id之类的东西

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

但是为了满足您的要求

我希望仅当sizeof...(Args) != 0时实例化ctor2

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM