作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我尝试编写一个 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/
我是一名优秀的程序员,十分优秀!