Reputation: 586
#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 */
// }
// }
Actually, now it seems impossible to me. Otherwise this class would inherit indefinite number of interface specializations...
But still, is it possible, at least for finite number of dimensions N?
template <template <typename> class C>
seems to be related, but I can't figure out how to apply this.
EDIT What I want is something like this:
class SomeTransformer :
public ITransformer<2>,
public ITransformer<3>,
public ITransformer<4>,
...,
public ITransformer<N> {
/* ... */
};
For any N ever used in code. This seems impossible, as I said.
Upvotes: 1
Views: 73
Reputation: 10315
You can achieve what you want or nearly that. Here's what I propose:
#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;
}
Now for any N
it will make SomeTransformer
inherit all ITransformer
from 1 to N.
Upvotes: 1
Reputation: 12263
Since N
is not declared anywhere, you cannot use it. You need something like:
class SomeTransformer : public ITransformer<5> {
public:
virtual void operator()(ITransformable<5>& transformable) const {
/* implementation */
}
};
or make it a template class:
template <uint32_t N>
class SomeTransformer : public ITransformer<N> {
public:
virtual void operator()(ITransformable<N>& transformable) const {
/* implementation */
}
};
UPDATE
There is no dynamic inheritance in C++. Therefore, what you want to achieve is not possible.
Upvotes: 1