我正在尝试制作一个模板,该模板可以推导与一个模板参数关联的类型,同时在非推导上下文中处理其他类型。下面提供了一个最小的示例。我可以使用两个演绎上下文来完成我要寻找的东西,但是可以一次完成吗?我以为我会尝试使用类似type_identity
的方法,但是我没有任何运气。
实时示例:https://onlinegdb.com/By0iDOM-P
template<size_t... Idx, size_t s>
void foo(index_sequence<Idx..., s>) {
cout << s << endl;
}
template<typename T>
struct TypeIdentity {
using Type = T;
};
template<typename T>
using Identity = typename TypeIdentity<T>::Type;
template<typename... Idx, size_t s>
void bar(index_sequence<Identity<Idx>{}..., s>) {
cout << s << endl;
}
template<size_t s>
void baz(index_sequence<0, s>) {
cout << s << endl;
}
template<size_t... Idx>
struct Qux {
template<size_t s>
static void qux(index_sequence<Idx..., s>) {
cout << s << endl;
}
};
int main()
{
foo<0>(make_index_sequence<2>{}); // couldn't deduce template parameter ‘s’
bar<integral_constant<size_t, 0>>(make_index_sequence<2>{}); // couldn't deduce template parameter ‘s’
baz(make_index_sequence<2>{});
Qux<0>::template qux(make_index_sequence<2>{});
return 0;
}
最佳答案
否。问题在于Idx...
包过于贪婪,无法为s
保留任何内容。您可以使用s, Idx...
来获取第一个值,但是不能使用Idx..., s
来获取最后一个值。 TypeIdentity
不能帮助您做到这一点,您还需要其他技巧。
例如,解压缩为数组(C++ 14):
template<std::size_t first, std::size_t... rest>
void foo(std::index_sequence<first, rest...>) {
const std::size_t indices[]{first, rest...};
const std::size_t last = indices[sizeof...(rest)];
std::cout << last << std::endl;
}
或将fold expression与comma operator(C++ 17)结合使用:template<std::size_t first, std::size_t... rest>
void foo(index_sequence<first, rest...>) {
const std::size_t last = (first, ..., rest);
std::cout << last << std::endl;
}
我隔离了first
以确保整个包first, rest...
永远不会为空。
关于c++ - 强制非推断上下文-type_identity等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63201976/