0

I have got a template class with 2 parameters and a fancy push_back method:

template<class Element, void (Element::*doWhenPushingBack)()> 
class StorableVector {
    public:
        ...
        void push_back(Handle< Element > e) {
            this->push_back_< IsNull<static_cast<void *>(doWhenPushingBack)>::value >(e);
        };
    private:
        template <int action> void push_back_(Handle< Element > e);
        template<> void push_back_<0>(Handle< Element > e) { m_elements.push_back(e); };
        template<> void push_back_<1>(Handle< Element > e) { ((*e).*(doWhenPushingBack))(); m_elements.push_back(e); };
        std::vector< Handle< Element > > m_elements;
};

It uses

template <void * param>   class IsNull {
public:
    enum {value = 0 };
};
template <>   
class IsNull<NULL> {
public:
    enum {value = 1 };
};

This piece of code does not compile( error C2440: 'static_cast' : cannot convert from 'void (__thiscall pal::InterfaceFunction::* const )(void)' to 'void *' 1> There is no context in which this conversion is possible).

Doing (!!doWhenPushingBack) check on runtime works fine, but looks a bit silly - check of compile time input needs to happen at compile time.

Could you help? Thanks.

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
Yulia V
  • 3,507
  • 10
  • 31
  • 64

2 Answers2

0

You can write

    void push_back(Handle< Element > e) {
        this->push_back_< doWhenPushingBack == 0 >(e);
    };

There's no need to use an IsNull template.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
0

You could have similar behaviour like this:

class Fred
{
public:
  void yabadabadoo() { std::cout << "yabadabadoo" << std::endl; }

  void wilma() { std::cout << "Wilmaaaaaaa!" << std::endl; }
};


template <typename E>
struct Nothing
{
  void operator()(E const &) const { }
};

template <typename E, void (E::* memfun)()>
struct Something
{
  void operator()(E e) const { (e.*memfun)(); }
};

template <typename E, typename Pre = Nothing<E>>
class MyVec
{
public:
  void push_back(E e) { Pre()(e); m_vec.push_back(e); }

protected:
private:
  std::vector<E> m_vec;
};


void stackoverflow() 
{
  MyVec<Fred> silent;
  MyVec<Fred, Something<Fred, &Fred::yabadabadoo>> yab;
  MyVec<Fred, Something<Fred, &Fred::wilma>> wil;

  Fred fred;
  silent.push_back(fred);
  yab.push_back(fred);
  wil.push_back(fred);
}

Any serious optimizing compiler (i.e. not older than 20 years or so) should optimize the empty function call of Nothing::operator() away.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
MadScientist
  • 3,390
  • 15
  • 19