C ++模板部分专业化:为什么我不能匹配可变参数模板中的最后一个类型? [英] C++ template partial specialization: Why cant I match the last type in variadic-template?

查看:68
本文介绍了C ++模板部分专业化:为什么我不能匹配可变参数模板中的最后一个类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写一个 IsLast 类型特征,以检查给定类型是否是 std :: tuple ,但是下面的代码无法编译。我知道如何解决这个问题,但我很好奇编译器为什么不喜欢它。我想必须对我不知道的可变参数模板的专业化有一些规定。

I try to write a IsLast type traits to check if a given type is the last one in a std::tuple, but the code below does not compile. I know how to get around it but I am curious why the compiler does not like it.I guess there must be some rule on specialization of variadic-template that I am not aware of.

代码位于: https://godbolt.org/g/nXdodx

错误消息:

error: implicit instantiation of undefined template
 'IsLast<std::tuple<std::__cxx11::basic_string<char>, int>, int>'

关于特殊化声明的警告:

There is also a warning on specialization declaration:


警告:类模板部分特殊化包含无法推导的模板参数;

warning: class template partial specialization contains template parameters that cannot be deduced; this partial specialization will never be used



#include <tuple>
#include <string>

/////////This works
template<typename TP, typename T>
struct IsFirst;

template<typename U, typename ...V, typename T>
struct IsFirst <std::tuple<U, V...>, T>
{
  enum {value = false};
};

template<typename U, typename ...V>
struct IsFirst <std::tuple<U, V...>, U>
{
  enum {value = true};
};

////////This doesn't compile
template<typename TP, typename T>
struct IsLast;

template<typename ...U, typename V, typename T>
struct IsLast <std::tuple<U..., V>, T>
{
  enum {value = false};
};

template<typename ...U, typename V>
struct IsLast <std::tuple<U..., V>, V>
{
  enum {value = true};
};


int main()
{
  using T = std::tuple<std::string, int>;
  bool v1 = IsFirst<T, std::string>::value;
  bool v2 = IsLast <T, int>::value;
}


推荐答案

在类模板中,参数包必须位于所有其他模板参数之后,因此不允许这样。

In a class template, the parameter pack must come after all other template parameters, so something like this is not allowed.

template<typename U, typename ...V, typename T>
struct IsFirst <std::tuple<U, V...>, T>
{
  enum {value = false};
};

在功能模板中,仅在可以推导的情况下,包之后才能有其他模板参数。类模板不允许这样做,因为它们不允许推导。

In a function template, there can be other template parameters after the pack only if they can be deduced. This is not allowed for class templates because they do not allow deduction.

这篇关于C ++模板部分专业化:为什么我不能匹配可变参数模板中的最后一个类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆