我需要实现对实现相同接口的对象向量的有效访问。到目前为止,我一直在使用虚函数的继承:接口被定义为具有纯虚函数的抽象类,每个对象类都实现虚函数。对象的向量只是抽象类上指针的向量(见消息的末尾,有一个动态访问的例子)。
我需要更快地访问对象集合。因为我在编译时知道所有可能的对象类,我使用boost::variant来实现对象集合(即boost::variant的向量)。我需要访问者方案的额外定义来遍历集合。为了明确所有对象实现相同的接口,我使用CRTP来获得静态继承:接口是CRTP抽象,每个对象类派生自模板化的CRTP抽象类。
下面是CRTP实现的一个示例。接口简单地定义了两个函数f()
和g(double)
。有两个派生类C1
和C2
实现了该接口(具有相同的行为)。
#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接口自动定义访问者?我想避免f_visitor
和g_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);
}
}
}
免责声明:这不是一个答案,只是一个可以用来解决给定问题的不同方法的基准。
这个想法是将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() << "sn";
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
和运行在Macbook Pro与2.6 GHz英特尔酷睿i7处理器和 16gb 1600 MHz DDR3 ram。
这些结果考虑了对原始代码的错误修复,以及@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
和包装器之间没有明显的赢家。