【发布时间】:2019-01-15 21:18:33
【问题描述】:
我正在创建一个从可变数量的类继承的class C。定义了这些类的列表,例如:A,B。在class C 的函数中,我需要调用所有基类的函数,但对象可以是C<A,B>、C<A> 或C<B>,所以如果我在C<B> 中调用class A 的函数,我会收到错误消息。以下是课程示例以及我如何尝试解决问题:
class A
{
int a;
public:
virtual void set_a(const int &value)
{
a = value;
}
protected:
virtual int get_a()
{
return this->a;
}
};
class B
{
int b;
public:
virtual void set_b(const int &value)
{
b = value;
}
protected:
virtual int get_b()
{
return this->b;
}
};
template<class ...T>
struct Has_A
{
template<class U = C<T...>>
static constexpr bool value = std::is_base_of < A, U > ::value;
};
template<class ...T>
class C :
virtual public T...
{
public:
#define HAS_A Has_A<T...>::value
void f()
{
#if HAS_A<>
auto a = this->get_a();
#endif
auto b = this->get_b();
cout << HAS_A<>;
}
};
当我调用对象C<A,B> 的f() 时,它会跳过调用get_a(),但输出是true。
一开始是我写的
template<class U = C<T...>>
typename std::enable_if<!std::is_base_of<A, U>::value, int>::type get_a()
{
return -1;
}
template<class U = C<T...>>
typename std::enable_if<std::is_base_of<A,U>::value, int>::type get_a()
{
return A::get_a();
}
但我不想为A 和B 的所有函数重写这个。假设A 还有10 个函数。
有什么好的解决办法吗?
P.S 对不起我的英语。我以前从未使用过 SFINAE。 基本上我有一堆基因,我想为它们编写方便的包装,可以配置他希望有机体拥有的基因。
【问题讨论】:
-
我不认为你的代码会编译:类模板
C在类模板Has_A中使用时没有定义。 -
你需要这个做什么?这看起来很奇怪。
标签: c++ c++11 templates variadic-templates template-meta-programming