简体   繁体   English

递归可变参数模板插入失败

[英]Recursive variadic template instation fails

What is the reason, that in the following example the instantiaton with three int is working with the second function template but not with the first one. 这是什么原因,在下面的示例中,具有三个int的实例正在使用第二个功能模板,而不使用第一个功能模板。 Additional: with the types State1 / State1 it isn't working either. 另外:对于类型为State1 / State1的任何一个都不起作用。

struct State1{};
struct State2{};

#if 0
template<typename none = void>
constexpr void f()
{
}
template<typename First, typename... Rest>
constexpr void f()
{
    f<Rest...>();
}
#else
template<typename none = void>
constexpr void f()
{
}
template<int First, int... Rest>
constexpr void f()
{
    f<Rest...>();
}
#endif
void test()
{
   f<1, 2, 3>();
//    f<State1, State2>();
}

Thank you any hints! 谢谢你的提示!

The problem in the first case is that both template specializations match when you pass a single template parameter (a parameter pack can be empty), so the overload set contains more than one candidate. 第一种情况的问题是,当您传递单个模板参数(参数包可以为空)时,两种模板专业化都匹配(因此,重载集包含多个候选)。 You can use SFINAE to make the second one fail to instantiate: 您可以使用SFINAE来使第二个实例化失败:

#include <type_traits>

struct State1{};
struct State2{};

template<typename none = void>
constexpr auto f() -> void
{
}

template<typename First, typename... Rest>
constexpr auto f() -> std::enable_if<sizeof...(Rest), void>::type
    // This will not instantiate when the parameter pack is empty
    // And the overload set will contain only the candidate above
{
    f<Rest...>();
}

int main()
{
  f<State1, State2>();

  return 0;
}

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

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