可变参数模板类,从其参数列表中获取特定类型的索引
Variadic template class, getting index of a specific type from its argument list
是否有可能实现可变参数模板类的函数成员,该函数成员从可变参数列表中返回给定类型的索引。
我看到的问题是创建某种伪造的可变参数列表,只是为了触发编译时模板评估。
template<typename... TArgs>
class Foo
{
template<typename T, typename TArg>
int _get_idx(int i, const TArg &curr, TArgs...args)
{
if (std::is_same(T, TArg)) {
return i;
}
else {
return get_id(i+1, args...);
}
}
用法如下:
Foo<A, B, C> foo;
int i = foo.get_idx<B>(); // i == 1
你可以使用这样的东西:
template <typename T, typename... Ts> struct get_index;
template <typename T, typename... Ts>
struct get_index<T, T, Ts...> : std::integral_constant<std::size_t, 0> {};
template <typename T, typename Tail, typename... Ts>
struct get_index<T, Tail, Ts...> :
std::integral_constant<std::size_t, 1 + get_index<T, Ts...>::value> {};
#if 1 // explicit error case, but you already have error without that.
template <typename T>
struct get_index<T>
{
// condition is always false, but should be dependant of T
static_assert(sizeof(T) == 0, "element not found");
};
#endif
现场示例
注意:您没有指定重复匹配类型会发生什么(所以我采用第一个(,如果类型不匹配,也不会(所以我做了一个编译时错误(
带有重复项的现场演示
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 有没有办法在从编译器获取参数时避免预处理器宏?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 如何从参数中获取函数签名?
- 获取可变参数模板参数包的相关类型
- 在 C++11 中获取函子作为参数
- 如何使用可变参数模板获取参数的变量号及其大小C++
- 是否可以获取成员函数模板参数的拥有对象?
- 如何从 x64 程序集中的堆栈中获取参数?
- 获取第一个模板参数的可靠方法
- 如何从参数包获取指向对象的指针
- C++ 如何使派生类自动获取基类参数
- 通过命令行参数获取llvm ir文件时面临问题
- 在C++中,是否允许将函数指针强制转换为将指向基类或派生类的指针作为参数获取的函数指针
- 使用一个可选参数获取两个参数到main
- cpp 映射作为函数参数获取警告信息 "discards qualifiers"
- 从控制台应用中的命令行参数获取文件名C++
- 从模板参数获取函数参数
- 使用参数获取其他参数