gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:32:13 25 4
gpt4 key购买 nike

我尝试编写一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com