【发布时间】:2020-10-17 22:18:42
【问题描述】:
我正在尝试使用std::conditional 来实现静态继承。
我的child 类有两个可能的父类,parent_one,它应该根据传递的类型保存多个变量,parent_two,它有两种类型。我正在使用标签调度来区分我想要继承的类。
现在解决问题。当我调用child 并将其标记为从parent_one 继承两种类型时,它按预期工作。但是,如果我尝试将任意数量的类型传递到 child 以从 parent_one 继承,则会出现错误:
static_polymorphism.cpp: In instantiation of ‘class child<foo_type, int, int, double, float>’:
static_polymorphism.cpp:110:41: required from here
static_polymorphism.cpp:99:7: error: wrong number of template arguments (4, should be 2)
99 | class child : public std::conditional_t<
| ^~~~~
static_polymorphism.cpp:90:7: note: provided for ‘template<class T, class F> class parent_two’
90 | class parent_two {
| ^~~~~~~~~~
static_polymorphism.cpp: In function ‘int main(int, char**)’:
static_polymorphism.cpp:111:9: error: ‘class child<foo_type, int, int, double, float>’ has no member named ‘log’
111 | first.log();
如果我理解正确,编译器应该根据我的标签调度生成代码。这意味着它应该从parent_one 创建重载类 - N(基于传递的类型)和来自parent_two 的M(基于传递的类型)。但是由于某种原因,我不知道,它不接受类型的变量计数。你能告诉我我做错了什么吗?
实施就在这里。
using one_t = struct foo_type{};
using two_t = struct bar_type{};
template <typename ... TYPES>
class parent_one {
public:
parent_one() = default;
void log() {
std::cout << "parent_one" << std::endl;
}
};
template <typename T, typename F>
class parent_two {
public:
parent_two() = default;
void log() {
std::cout << "parent_two" << std::endl;
}
};
template <typename T, typename ... ARGS>
class child : public std::conditional_t<
std::is_same_v<T, one_t>,
parent_one<ARGS...>,
parent_two<ARGS...>
>
{
public:
child() = default;
};
int main(int argc, char *argv[]) {
child<one_t, int, int, double, float> first;
first.log();
child<two_t, int, int> second;
second.log();
return 0;
}
【问题讨论】: