0

我有一个带有 2 个参数的模板类和一个花哨的 push_back 方法:

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;
};

它用

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

这段代码无法编译(错误 C2440: 'static_cast' : 无法从 'void (__thiscall pal::InterfaceFunction::* const )(void)' 转换为 'void *' 1> 没有进行此转换的上下文是可能的)。

在运行时执行 (!!doWhenPushingBack) 检查工作正常,但看起来有点傻 - 编译时输入的检查需要在编译时进行。

你能帮忙吗?谢谢。

4

2 回答 2

0

您可能会有类似的行为:

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);
}

任何认真的优化编译器(即不超过 20 年左右)都应该优化 Nothing::operator() 的空函数调用。

于 2012-08-22T11:30:18.627 回答
0

你可以写

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

无需使用IsNull模板。

于 2012-08-22T11:07:56.757 回答