Domanda

I am using the type erasure design pattern to expose a template-independent interface for one of my template classes. However, I have run into the problem that one of the methods that I wish to expose, which fuses two templated instances into a third instance with a different template constant parameter argument, seems to require template virtual methods, which are illegal.

This is my code:

#include <stdlib.h>

template<size_t N>
class bar
{
    template<size_t M>
    bar<M+N> fuse(const bar<M>& rhs) { return bar<M+N>(); }
};

class bar_any_N 
{
private:
    class abstract_base
    {
        virtual bar_any_N fuse(const abstract_base* rhs) = 0;

        template<size_t M>
        virtual bar_any_N fuse_accept(const bar<M>& lhs) = 0;
    };

    template<size_t N>
    class wrapper : public abstract_base
    {
    private:
        bar<N> m_bar;
    public:
        wrapper(const bar<N>& the_bar) : m_bar(the_bar) { }

        bar_any_N fuse(const abstract_base* rhs) { return rhs->fuse_accept(*this); }

        template<size_t M>
        bar_any_N fuse_accept(const bar<M>& lhs) { return lhs.m_bar.fuse(this->m_bar) }
    };

    abstract_base* m_ptr;
public:
    template<size_t N> 
    bar_any_N(const bar<N>& the_bar) { m_ptr = new wrapper<N>(the_bar); }

};

int main()
{
    bar<1> b1;
    bar<2> b2;
    bar_any_N b1_erased(b1);
    bar_any_N b2_erased(b2);

    bar_any_N b3 = b1_erased.fuse(b2_erased);

    return 0;
}

Does anyone have another way to implement this that would not require a virtual template member?

EDIT: The purpose of this 'template independent interface' is to pass vectors of bar instances with different template parameters to functions:

std::vector< bar_any_N > vec; 
vec.push_back(bar<2>()); 
vec.push_back(bar<5>()); 
foo_func(vec); 

EDIT:

Here is a simpler working example with a printing method instead of the above fuse method that shows how I would LIKE this to work:

http://codepad.org/8UbJguCR

È stato utile?

Soluzione

Do inside out type erasure.

struct bar_raw
{
  std::size_t N;
  explicit bar_raw( std::size_t n ):N(n) {}
  bar_raw fuse( const bar_raw& rhs ) { return bar_raw(N+rhs.N); }
};
template<size_t N>
struct bar: bar_raw
{
  bar():bar_raw(N) {}
  template<size_t M>
  bar<M+N> fuse(const bar<M>& rhs) { return bar<M+N>(); }
};

Keep all state in bar_raw. Have a pretty interface that helps writing code in bar<N>, like n-ary indexes.

When passed a bar<N> to type erase, you ignore the bar<N> component and type erase the bar_raw, which is pretty trivial.

You could call bar_raw your bar_any if you wanted, or you could leave bar_raw as an implementation detail, and wrap it in a bar_any that is all pretty.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top