继承模板类中的类型别名
Inheritting type aliases in template classes
我想做这样的事情:
- 我的库定义了一个结构
LibStruct
- 库的客户端构建自己的结构,这些结构以某种方式相关(在示例中,我使用了继承,但也许有更好的表达方式(
- 该库有一个使用这些结构执行一些操作的方法 避免
- 虚函数调用(硬要求(和避免联合/变体(软要求(
到目前为止,我一直在做的是:
template <typename T /** And a bunch more **/>
struct LibStruct {
using Scalar = T;
// And a bunch more aliases
// Some data
};
template <typename T>
struct ClientStuctA : LibStruct<T> {
using Scalar = T; // Can this be avoided?
Scalar moreData;
};
struct ClientStuctB : LibStruct<double> {
using Scalar = double; // Can this be avoided?
Scalar otherData;
};
template <typename Whatever>
typename Whatever::Scalar doSomething(const Whatever& input) {
// Do stuff
return Whatever::Scalar();
}
我的问题是所有客户端结构都需要重新定义所有别名,以便doSomething
可以使用它们。有没有办法避免这种需求?
(要求C++14
,但如果有C++17
解决方案,我也会接受(
所以总结一下我和@N.Shead在评论中的来回,由这些链接支持,为什么你不能做得更好:
将"typedef"从 based 类传播到"模板"的派生类
C++中的继承和模板 - 为什么继承的成员不可见?
这似乎是我们能做的最好的事情:
#include <iostream>
template<typename T /* And a bunch more */>
struct LibStruct {
using Scalar = T;
// ... and a lot more aliases
};
#define LIBSTRUCT_TYPES(base)
using Scalar = typename base::Scalar;
// ... and a lot more
template<typename T>
struct ClientStuctA : LibStruct<T> {
LIBSTRUCT_TYPES(LibStruct<T>)
Scalar moreData;
// OtherTypes moreDefinitions();
Scalar func1() { return Scalar(2) * 3; }
Scalar func2();
};
template<typename T>
typename ClientStuctA<T>::Scalar ClientStuctA<T>::func2() {
return 5;
}
int main() {
std::cout << ClientStuctA<int>().func1() << std::endl;
std::cout << ClientStuctA<int>().func2() << std::endl;
return 0;
}
相关文章:
- 继承模板类中的类型别名
- 为什么 GCC 在使用类型别名时处理 const reinterpret_cast不同?
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 如何使用类型别名从模板化类中隐藏模板列表
- 如何检测类型类型别名?
- C++类型别名,其中值被替换
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 通过类型别名从构造函数转发模板推导
- C++中的严格别名规则和类型别名
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 什么是C++中的类型别名?
- 如何在不违反类型别名规则的情况下解释消息负载?
- 在模板派生类中继承具有类型别名的构造函数
- 类型别名允许分配任意指针,尽管 int* 是必需的
- 使用类型别名,例如使用 A = int(int)
- 模板类函数指针类型别名
- 类型别名和类似类型
- 泛型类型别名,它们彼此不兼容
- 具有类型别名的循环依赖项
- 为什么模板引用类型不能用作模板类型别名参数?