继承模板类中的类型别名

Inheritting type aliases in template classes

本文关键字:类型 别名 继承      更新时间:2023-10-16

我想做这样的事情:

  • 我的库定义了一个结构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;
}