首页 > 解决方案 > 具有非专用模板参数的虚拟方法

问题描述

#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。正如我所说,这似乎是不可能的。

标签: c++templatesc++14template-specialization

解决方案


由于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++中没有动态继承。因此,您想要实现的目标是不可能的。


推荐阅读