c++ - 具有非专用模板参数的虚拟方法

标签 c++ templates c++14 template-specialization

#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> { 
    /* ... */ 
};

对于任何 曾经在代码中使用过。正如我所说,这似乎是不可能的。

最佳答案

你可以达到你想要的或接近的。这是我的建议:


#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继承所有ITransformer从 1 到 N。

关于c++ - 具有非专用模板参数的虚拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60770896/

相关文章:

c++ - 如何创建一个新变量并同时在 std::tie 中使用它?

c++ - 在对任意区域有限制的二维空间中找到有效点

C++ 用个位数和两位数排列间距

c++ - 显式实例化泛型结构的泛型成员函数

c++ - 没有默认构造函数的模板的模板

c++ - 在 Travis 服务器上使用 Buck 构建

c++ - 返回转发引用参数 - 最佳实践

c++ - Opencv Mat - 访问冲突错误 C++

c++ - 识别(编程)语言的关键字

c++ - 可以将c++运算符的功能名称制作为模板吗?