2

我需要实现对实现相同接口的对象向量的有效访问。到目前为止,我一直在使用虚函数的继承:接口被定义为具有纯虚函数的抽象类,并且每个对象类都实现了虚函数。对象向量只是抽象类上的指针向量(参见消息末尾的动态访问示例)。

我需要更快地访问对象集合。因为我在编译时知道所有可能的对象类,所以我使用 boost::variant 来实现对象集合(即 boost::variant 的向量)。我需要访客计划的额外定义才能通过集合。为了明确表示所有对象都实现相同的接口,我使用 CRTP 来获得静态继承:接口是 CRTP 抽象,并且每个对象类都派生自模板化的 CRTP 抽象类。

这是 CRTP 实现的示例。该接口简单地定义了两个函数f()g(double). 有两个派生类C1C2实现接口(具有相同的行为)。

#include <vector>
#include <boost/foreach.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/variant.hpp>

namespace testVariantSimple
{

  // Definition of the interface (abstract class).
  template< typename C >
  struct CBase
  {
    void f() { static_cast<C&>(*this).f(); }
    int g(const double & x) { return static_cast<C&>(*this).g(x); }
  };

  // Definition of the first implementation.
  struct C1 : public CBase<C1>
  {
    void f();
    int g(const double & x);
  };
  void C1::f() { return ; }
  int C1::g(const double & x) { return sizeof(x); }

  // Definition of the second implementation.        
  struct C2 : public CBase<C2>
  {
    void f();
    int g(const double & x);
  };
  void C2::f() { return ; }
  int C2::g(const double & x) { return sizeof(x); }

  // Definition of the visitor for the first function of the interface.  
  class f_visitor : public boost::static_visitor<int>
  {
  public:
    template< typename C >
    int operator()(CBase<C> &c ) const { c.f(); return 0; }
  };

  // Definition of the visitor for the second function of the interface.  
  struct g_visitor : public boost::static_visitor<int>
  {
    const double & x;
    g_visitor( const double & x ) : x(x) {}
  public:
    template< typename C >
    int operator()(CBase<C> & c) const { return c.g(x);  }
  };

  // Example of use: construct a random collection and visit it.
  void test(int nbSample)
  {
    typedef boost::variant<C1,C2> CV;
    std::vector<CV> vec;

    for( int i=0;i<nbSample;++i ) 
      {
    switch( std::rand() % 2 )
      {
      case 1:       vec.push_back( C1() ); break;
      case 2:       vec.push_back( C2() ); break;
      }
      }

    double argdouble;
    BOOST_FOREACH(CV & c, vec)
      {
    boost::apply_visitor( f_visitor(), c );
    g_visitor g(argdouble);
    boost::apply_visitor( g, c );
      }
  }
}

这段代码有效,并且比使用动态继承的代码效率高 15 倍(有关使用动态的代码,请参见消息末尾)。对于不熟悉 CRTP 的人来说,代码阅读起来稍微困难一些,但维护或编写起来并不困难。由于 CRTP 的接口是显式的,因此访问者实现相当琐碎,但冗长,难以理解和使用。

我的问题很简单:是否可以从 CRTP 界面自动定义访问者。我想避免 and 的额外定义f_visitorg_visitor并获得更易读的外观:

   BOOST_FOREACH( CV & c, vec )
   {
      c.f();
      c.g(argdouble);
   }

谢谢你的帮助。对于感兴趣的读者,这里是使用虚拟继承的相同代码。

namespace testDynamicSimple
{
  struct CBase
  {
    virtual void f() = 0;
    virtual int g(const double & x) = 0;
  };

  struct C1 : public CBase  
  {
    void f() {}
    int g(const double & x) { return 1; }
  };
  struct C2 : public CBase
  {
    void f() {}
    int g(const double & x) { return 2; }
  };

  bool test(int nbSample)
  {
    typedef boost::shared_ptr<CBase> CV;
    std::vector<CV> vec;
    for( int i=0;i<nbSample;++i ) 
      {
    switch( std::rand() % 5 )
      {
      case 1:       vec.push_back( CV(new C1()) ); break;
      case 2:       vec.push_back( CV(new C2()) ); break;
      }
      }

    double argdouble = 0.0;
    BOOST_FOREACH( CV & c, vec)
    {
      c->f();
      c->g(argdouble);
    }
  }
}
4

1 回答 1

1

免责声明:这不是答案,只是可用于解决给定问题的不同方法的基准。

这个想法是将其boost::variant与其他技术(原始指针上的虚函数、共享指针上的虚函数以及其他一些技术)进行比较。这是我使用的基准代码:

#include <vector>
#include <boost/foreach.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/variant.hpp>
#include <memory>
#include <type_traits>

namespace novirtual {

  struct C {
    void f() {}
    int g(const double &x) { return 1; }
  };

  void test(int nbSample) {

    std::vector<C> vec;
    vec.reserve(nbSample);
    for (int i = 0; i < nbSample; ++i)
      vec.emplace_back(C());

    double argdouble = 0.0;
    BOOST_FOREACH(C &c, vec) {
      c.f();
      c.g(argdouble);
    }
  }
}
namespace crtp {

// Definition of the interface (abstract class).
template <typename C> struct CBase {
  void f() { static_cast<C &>(*this).f(); }
  int g(const double &x) { return static_cast<C &>(*this).g(x); }
};

// Definition of the first implementation.
struct C1 : public CBase<C1> {
  void f();
  int g(const double &x);
};
void C1::f() { return; }
int C1::g(const double &x) { return sizeof(x); }

// Definition of the second implementation.
struct C2 : public CBase<C2> {
  void f();
  int g(const double &x);
};
void C2::f() { return; }
int C2::g(const double &x) { return sizeof(x); }

// Definition of the visitor for the first function of the interface.
class f_visitor : public boost::static_visitor<int> {
public:
  template <typename C> int operator()(CBase<C> &c) const {
    c.f();
    return 0;
  }
};

// Definition of the visitor for the second function of the interface.
struct g_visitor : public boost::static_visitor<int> {
  const double &x;
  g_visitor(const double &x) : x(x) {}

public:
  template <typename C> int operator()(CBase<C> &c) const { return c.g(x); }
};

// Example of use: construct a random collection and visit it.
void test(int nbSample) {
  typedef boost::variant<C1, C2> CV;
  std::vector<CV> vec;
  vec.reserve(nbSample);
  for (int i = 0; i < nbSample; ++i) {
    switch (std::rand() % 2) {
    case 0:
      vec.push_back(C1());
      break;
    case 1:
      vec.push_back(C2());
      break;
    }
  }

  double argdouble;
  BOOST_FOREACH(CV & c, vec) {
    boost::apply_visitor(f_visitor(), c);
    g_visitor g(argdouble);
    boost::apply_visitor(g, c);
  }
}
}

namespace virt_fun {
struct CBase {
  virtual void f() = 0;
  virtual int g(const double &x) = 0;
};

struct C1 : public CBase {
  void f() {}
  int g(const double &x) { return 1; }
};
struct C2 : public CBase {
  void f() {}
  int g(const double &x) { return 2; }
};

void test(int nbSample) {
  std::vector<CBase *> vec;
  vec.reserve(nbSample);
  for (int i = 0; i < nbSample; ++i) {
    switch (std::rand() % 2) {
    case 0:
      vec.push_back(new C1());
      break;
    case 1:
      vec.push_back(new C2());
      break;
    }
  }

  double argdouble = 0.0;
  BOOST_FOREACH(CBase * c, vec) {
    c->f();
    c->g(argdouble);
  }
}
}

namespace shared_ptr {
struct CBase {
  virtual void f() = 0;
  virtual int g(const double &x) = 0;
};

struct C1 : public CBase {
  void f() {}
  int g(const double &x) { return 1; }
};
struct C2 : public CBase {
  void f() {}
  int g(const double &x) { return 2; }
};

void test(int nbSample) {
  typedef boost::shared_ptr<CBase> CV;
  std::vector<CV> vec;
  vec.reserve(nbSample);
  for (int i = 0; i < nbSample; ++i) {
    switch (std::rand() % 2) {
    case 0:
      vec.push_back(CV(new C1()));
      break;
    case 1:
      vec.push_back(CV(new C2()));
      break;
    }
  }

  double argdouble = 0.0;
  BOOST_FOREACH(CV & c, vec) {
    c->f();
    c->g(argdouble);
  }
}
}

namespace virt_cont {

struct CBase {
  virtual void f() = 0;
  virtual int g(const double &x) = 0;
  virtual ~CBase() = default;
};

struct C1 final : public CBase {
  void f() {}
  int g(const double &x) { return 1; }
};
struct C2 final : public CBase {
  void f() {}
  int g(const double &x) { return 2; }
};

struct foo {
  std::aligned_storage<sizeof(C2)>::type buf;
  CBase *ptr;

  foo(C1 c) { ptr = new ((void *)&buf) C1(c); }
  foo(C2 c) { ptr = new ((void *)&buf) C2(c); }

  foo(foo &&x) : buf(x.buf) { ptr = reinterpret_cast<CBase *>(&buf); } // UB

  foo &operator=(foo &&x) {
    buf = x.buf;
    return *this;
  } // maybe UB?

  ~foo() { ptr->~CBase(); }
};
void test(int nbSample) {
  std::vector<foo> vec;
  vec.reserve(nbSample);
  for (int i = 0; i < nbSample; ++i) {
    switch (std::rand() % 2) {
    case 0:
      vec.emplace_back(C1());
      break;
    case 1:
      vec.emplace_back(C2());
      break;
    }
  }

  double argdouble = 0.0;
  BOOST_FOREACH(foo & c, vec) {
    c.ptr->f();
    c.ptr->g(argdouble);
  }
}
}

namespace locals {
struct CBase {
  virtual void f() = 0;
  virtual int g(const double &x) = 0;
  virtual ~CBase() = default;
};

struct C1 final : public CBase {
  void f() {}
  int g(const double &x) { return 1; }
};
struct C2 final : public CBase {
  void f() {}
  int g(const double &x) { return 2; }
};

void test(int nbSample) {
  C1 c1;
  C2 c2;

  std::vector<CBase *> vec;
  vec.reserve(nbSample);
  for (int i = 0; i < nbSample; ++i) {
    switch (std::rand() % 2) {
    case 0:
      vec[i] = &c1;
      break;
    case 1:
      vec[i] = &c2;
      break;
    }
  }

  double argdouble = 0.0;
  BOOST_FOREACH(CBase * c, vec) {
    c->f();
    c->g(argdouble);
  }
}
}

#include <chrono>
#include <string>

#define VER 4

int main(int argc, char *argv[]) {

  int n = 100000;
  for (int i = 0; i < 4; ++i) {

    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();

#if VER == 0
    virt_fun::test(n);
#elif VER == 1
    shared_ptr::test(n);
#elif VER == 2
    crtp::test(n);
#elif VER == 3
    virt_cont::test(n);
#elif VER == 4
    locals::test(n);
#endif

    end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end - start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";

    n *= 10;
  }
  return 0;
}

代码编译clang++ -O3 main.cpp -I/Users/aaragon/Local/include

$ clang++ --version
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix

并在配备2.6 GHz Intel Core i7处理器和16 GB 1600 MHz DDR3内存的 Macbook Pro 上运行。

这些结果考虑了对原始代码的错误修复,以及@dyp 提供的使用包装类的附加代码std::aligned_storage。在下表中,该no virtual列对应于根本没有继承,并作为参考给出。

  |    size   | no virtual| raw ptr   | shared_ptr |  variant  | wrapper   |  locals   |
  |-----------|-----------|------------|-----------|-----------|-----------|-----------|
  |    100000 | 0.000235s | 0.008309s |  0.030801s | 0.003935s | 0.004222s | 0.001925s |
  |   1000000 | 0.002053s | 0.061843s |  0.288403s | 0.029874s | 0.033697s | 0.01478s  |
  |  10000000 | 0.017687s | 0.627659s |  2.91868s  | 0.29699s  | 0.322109s | 0.141245s |
  | 100000000 | 0.177425s | 6.2493s   | 28.9586s   | 3.00427s  | 3.21402s  | 1.40478s  |

在这个阶段,有些事情是确定的:boost::shared_ptr非常慢,并且在boost::variant和包装器之间没有明确的赢家。

于 2014-08-19T09:16:14.890 回答