#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 */
// }
// }
实际上,现在对我来说似乎是不可能的。否则,此类将继承
接口(interface)特化的数量不确定...
但是仍然有可能,至少对于有限数量的尺寸N?
template <template <typename> class C>
似乎相关,但是我不知道如何应用它。编辑
我想要的是这样的:
class SomeTransformer :
public ITransformer<2>,
public ITransformer<3>,
public ITransformer<4>,
...,
public ITransformer<N> {
/* ... */
};
对于代码中曾经使用的任何 N 。正如我所说,这似乎是不可能的。
最佳答案
您可以实现自己想要的或接近实现的目标。这是我的建议:
#include <type_traits>
#include <utility>
template<std::size_t N>
struct ITransformer {};
template<class T>
class SomeTransformer_h { };
template<std::size_t... Indices>
class SomeTransformer_h<
std::integer_sequence<std::size_t, Indices...>> :
public ITransformer<1 + Indices>... { };
template<std::size_t N>
class SomeTransformer : public SomeTransformer_h<
std::make_index_sequence<N>
> { };
int main() {
SomeTransformer<5> a;
ITransformer<1>& ref = a;
ITransformer<4>& ref2 = a;
ITransformer<5>& ref3 = a;
}
现在,对于任何
N
,它将使SomeTransformer
继承从1到N的所有ITransformer
。