繁体   English   中英

具有非特化模板参数的虚方法

[英]Virtual method with unspecialized template argument

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

您可以实现您想要的或几乎达到的目标。 这是我的建议:


#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM