C++ 模板部分特化 : Why cant I match the last type in variadic-template?

标签 c++ c++11 variadic-templates template-meta-programming template-specialization

我尝试编写一个 IsLast 类型特征来检查给定类型是否是 std::tuple 中的最后一个类型,但下面的代码无法编译。我知道如何绕过它,但我很好奇为什么编译器不喜欢它。我想一定有一些我不知道的关于可变参数模板特化的规则。

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

错误信息:

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

还有关于特化声明的警告:

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

最佳答案

在类模板中,参数包必须在所有其他模板参数之后,所以这样的事情是不允许的。

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

在一个函数模板中,pack 后面可以有其他模板参数,只要它们可以推导即可。这对于类模板是不允许的,因为它们不允许推导。

关于C++ 模板部分特化 : Why cant I match the last type in variadic-template?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42042691/

相关文章:

c++ - 了解默认 move 构造函数定义

c++ - 在可变参数模板中实现 STL 函数

c++ - 如何正确包装第 3 方库结构?

c++ - C++中的不同数字

C++ auto ,不明白如何分配运算符?

c++ - 右值引用对象内部的对象是否也被右值引用?

c++ - 尝试根据类中 typedef 的存在来专门化模板函数

c++ - 模棱两可的错误 : C++11 use variadic template multiple inheritance

C++ 函数指针

C++ : Reading File contents into wstring