考虑这段代码:
enum Brand {a,b,c,d,e,f,g,h,i,j};
template <Brand, int> struct A {};
struct B : A<a,4>, A<d,0>, A<i,3> {};
struct C : A<b,0>, A<c,5>, A<e,1>, A<h,4>, A<j,0> {};
template <typename, Brand...> void foo() {}
int main() {
foo<B, a,d,i>();
foo<C, b,c,e,h,j>();
}
foo<B, a,d,i>();
只有在我的(真正的)程序中有 a,d,i
才有意义作为参数,因为 B 的多重继承。然而,a,d,i
应该以某种方式推导,否则如果我更改 B 的继承,将会出现维护问题。 foo<C, b,c,e,h,j>();
也是如此
我写不出 template <typename T> struct GetBrands
获得Brand
的可推导包来自 T
的元素.任何帮助,将不胜感激。现在,我们假设 A 中的最高 int 值为 10。
最佳答案
如果我们将问题转过来并(稍微)改变您编写 B
和 C
类定义的方式会怎么样?
下面,我从你的答案中借用了测试代码:
#include <iostream>
enum Brand {a,b,c,d,e,f,g,h,i,j};
template<Brand, int> struct A { };
template<typename...> struct A_base;
template<Brand... Brands, int... Is> struct A_base<A<Brands, Is>...> : A<Brands, Is>... { };
struct B : A_base<A<a,4>, A<d,0>, A<i,3>> { };
struct C : A_base<A<b,0>, A<c,5>, A<e,1>, A<h,4>, A<j,0>> { };
//template<typename, Brand...> void foo() { }
// *Overloading* foo in order to test the outputs.
template<typename, Brand x, Brand y, Brand z>
void foo() { std::cout << x << ' ' << y << ' ' << z << '\n'; }
template<typename, Brand x, Brand y, Brand z, Brand u, Brand v>
void foo() { std::cout << x << ' ' << y << ' ' << z << ' ' << u << ' ' << v << '\n'; }
template<typename S, Brand... Brands, int... Is> void foo_helper(A_base<A<Brands, Is>...>)
{
foo<S, Brands...>();
}
template<typename S> void bar() { foo_helper<S>(S()); }
int main()
{
bar<B>(); // Supposed to be the same as foo<B, a,d,i>(); // 0 3 8
bar<C>(); // Supposed be the same as foo<C, b,c,e,h,j>(); // 1 2 4 7 9
}
我认为这可以用来处理您需要的更一般的情况。
关于c++ - 从多重继承中确定模板包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30178909/