c++ - 从多重继承中确定模板包

标签 c++ templates c++11 inheritance

考虑这段代码:

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。

最佳答案

如果我们将问题转过来并(稍微)改变您编写 BC 类定义的方式会怎么样?

下面,我从你的答案中借用了测试代码:

#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/

相关文章:

c++ - 标准容器元素的常量正确性

c++ - 使用链接器选择 C++ 函数的实现

c++ - 函数模板实例的地址可以作为函数指针传递给某个函数吗?

c++ - 是否可以根据模板参数的条件排除模板成员变量?

c++ - 重载本地 lambda 函数

c++ - 生成器模式 : making sure the object is fully built

c++ - iOS Vuforia从后台进入后出现错误

c++ - 如何使用 std::array 模拟 C 数组初始化 "int arr[] = { e1, e2, e3, ... }"行为?

c++ - 为什么我不能用 const_iterator 调用模板基类构造函数?

c++ - CUDA 8 编译错误 -std=gnu++11