2012-03-09 79 views
4

我想以某种方式定义一个基本模板类,以便它采用可变参数模板参数并为每个参数定义一个虚拟方法,其中参数是参数类型。使用可变参数模板的参数定义多个方法

E.g. Base<int, bool, string>应该给我3个虚拟方法:Foo(int),Foo(bool)Foo(string)

我试过如下:

template <typename Param> 
struct BaseSingle 
{ 
    virtual void Foo(Param) {}; 
}; 

template <typename... Params> 
struct Base : public BaseSingle<Params>... 
{ 
}; 

不幸的是,富变得模糊。我无法获得​​语法的工作。有没有办法?

我知道,或者,我可以从BaseSingle递归继承并传递其余的参数。这是否有性能影响?

+0

递归继承是正常的,例如, 'std :: tuple'就是这样实现的。我不明白你为什么会遇到性能问题,你的函数甚至不会相互覆盖,也不会在运行时调用overriden成员来传递参数。 – doublep 2012-03-09 20:40:19

+0

[在variadic模板中使用声明]的可能的重复(http://stackoverflow.com/questions/7870498/using-declaration-in-variadic-template) – 2012-03-09 20:46:39

+2

* std :: tuple的一些*实现使用递归继承。但好的不是。 ;-) – 2012-03-09 21:51:31

回答

5

这是一个需要精确的类型匹配的建议:

#include <utility> 
#include <typeinfo> 
#include <string> 
#include <iostream> 
#include <cstdlib> 
#include <memory> 

#include <cxxabi.h> 

using namespace std; 

// GCC demangling -- not required for functionality 
string demangle(const char* mangled) { 
    int status; 
    unique_ptr<char[], void (*)(void*)> result(
    abi::__cxa_demangle(mangled, 0, 0, &status), free); 
    return result.get() ? string(result.get()) : "ERROR"; 
} 

template<typename Param> 
struct BaseSingle { 
    virtual void BaseFoo(Param) { 
    cout << "Hello from BaseSingle<" 
     << demangle(typeid(Param).name()) 
     << ">::BaseFoo" << endl; 
    }; 
}; 

template<typename... Params> 
struct Base : public BaseSingle<Params>... { 
    template<typename T> void Foo(T&& x) { 
    this->BaseSingle<T>::BaseFoo(forward<T>(x)); 
    } 
}; 

int main() { 
    Base<string, int, bool> b; 
    b.Foo(1); 
    b.Foo(true); 
    b.Foo(string("ab")); 
} 

但IMO采用递归继承自己的建议听起来更高雅。

+0

你需要一个'std :: make_unique '设施:)对于'demangle'中那个混乱的混乱。有趣的东西 – sehe 2012-03-09 21:52:51

+0

我试过这个,并且'Derived'继承自'Base'。看起来'this-> BaseSingle :: BaseFoo'不会调用重写的Derived'Foo',而是调用基本的,这是虚拟功能业务的重点。 – 2012-03-09 22:38:58

+0

@Msoul将它重写为'BaseSingle * base = this; base-> BaseFoo(转发(x));'让你的虚拟发送回 – je4d 2012-03-09 22:52:22

相关问题