c++ - 具有非专用模板参数的虚拟方法
问题描述
#include <iostream>
#include <array>
#include <vector>
using namespace std;
// Currently I have code much like this one:
template <const uint32_t N>
using VectorN = array<double, N>;
template <const uint32_t N>
class ITransformable {
public:
virtual vector<VectorN<N>>& positions() = 0;
};
class SomeTransformer {
public:
template <const uint32_t N>
void operator()(ITransformable<N>& transformable) const {
/* implementation */
}
};
// Then I want to create interface like this.
template <const uint32_t N>
class ITransformer {
public:
virtual void operator()(ITransformable<N>& transformable) const = 0;
};
// And finally implement it for SomeTransformer:
//
// Notice that class is not template, this is intentional.
//
// class SomeTransformer : public ITransformer<N> {
// public:
// virtual void operator()(ITransformable<N>& transformable) const {
// /* implementation */
// }
// }
实际上,现在对我来说似乎是不可能的。否则这个类将继承无限数量的接口特化......
但是,至少对于有限数量的维度N是否有可能?
template <template <typename> class C>
似乎是相关的,但我不知道如何应用它。
编辑 我想要的是这样的:
class SomeTransformer :
public ITransformer<2>,
public ITransformer<3>,
public ITransformer<4>,
...,
public ITransformer<N> {
/* ... */
};
对于代码中曾经使用过的任何N。正如我所说,这似乎是不可能的。
解决方案
由于N
未在任何地方声明,因此您不能使用它。你需要类似的东西:
class SomeTransformer : public ITransformer<5> {
public:
virtual void operator()(ITransformable<5>& transformable) const {
/* implementation */
}
};
或使其成为模板类:
template <uint32_t N>
class SomeTransformer : public ITransformer<N> {
public:
virtual void operator()(ITransformable<N>& transformable) const {
/* implementation */
}
};
更新
C++中没有动态继承。因此,您想要实现的目标是不可能的。
推荐阅读
- javascript - 数据结构过滤
- rx-java2 - Vertx 网络和 graphql
- android - Android id is change 同一个app运行在两个不同的Monitor和apk build上怎么解决?请告诉我答案
- php - 在 PHP/Symfony 中匹配 2 个用户函数
- google-chrome-extension - 您能否更好地为 Chrome 扩展清单中的主机权限定义 file:/// URL 模式?
- r - 运行 spacyr 错误找不到 ludwig/python.exe
- python - 如何为以下字典创建 json 字符串
- python - 如果向量相同,计算两个向量之间角度的方法会引发错误?
- python - 将列表和数据框传递给具有不同行为的 python 函数
- rest - 连接基于 Vue 的 Web 应用程序时如何保护我的后端 API