c++ - 如何继承不适用于基类实例的模板构造函数?
问题描述
我有很多来自基类的派生类。这些类必须从基类继承构造函数,但该构造函数只能与派生类或基类实例一起使用。
基类示例:
template<typename T, typename U>
struct bar
{
bar() = default;
template<typename _Bar_or_Derived>
bar(const _Bar_or_Derived &); // must accept any bar or its derived classes
};
派生类示例:
template<typename T, typename U>
struct foo : public bar<T, U>
{
using bar<T, U>::bar;
// must inherit something like foo(const Foo_or_Bar&)
};
template<typename T, typename U>
struct not_foo : public bar<T, U>
{
using bar<T, U>::bar;
// must inherit something like not_foo(const NotFoo_or_Bar&)
};
怎么做这样的事情?
解决方案
似乎您想要CRTP而不是通用基类以避免重复代码:
template <typename > struct Bar;
template <template <typename, typename> class C, typename T1, typename T2>
struct Bar<C<T1, T2>>
{
Bar(const Bar&) {/*..*/}
template <typename U1, U2>
Bar(const Bar<C<U1, U2>>&) {/*..*/}
template <typename U1, U2>
Bar(const C<U1, U2>&) {/*..*/}
};
// Maybe you just need template <template <typename, typename> class C> struct Bar{};
// instead, as T1, T2 seems not used
template<typename T, typename U>
struct foo : public bar<foo>
{
using bar<foo>::bar;
};
template<typename T, typename U>
struct not_foo : public bar<not_foo>
{
using bar<not_foo>::bar;
};
推荐阅读
- r - 基于R中另一列中的排序创建列
- xml - 找到父母兄弟姐妹的xpath
- sql-server-2008 - 如何将多行连接成一个
- pandas - 用 pandas 数据框制作多个饼图(每列一个)
- python - Tensorflow 2.0:在放入 model.fit_generator 之前预处理从 ImageDataGenerator 生成的输入数据
- java - 连接到 MySQL 时正则表达式中的语法错误
- snowflake-cloud-data-platform - 使用 Snowflake 凭据连接到 SnowSQL 客户端
- python - 在减法问题python中只得到肯定的答案
- python - 如何在 python Apscheduler Backgroundscheduler 中添加多个作业?
- angular - 用于通用逻辑的 Angular using 指令