2017-04-05 19 views
0

是否可以实现这样的行为?它不必使用继承,我只想实现具有通用参数传递的模板方法设计模式(使用C++模板)。创建一个类方法模板,它将使用稍后实现的函数

class A { 
public: 
    template<typename ...tArgs> 
    void call(tArgs ...vArgs) { 
     for (int i = 0; i < 5; ++i) 
      impl(vArgs...); 
    } 
}; 

class B : public A { 
public: 
    void impl() {} 
    void impl(int) {} 
}; 

int main() { 
    B b; 
    b.call(); // ok 
    b.call(1); // ok 
    b.call(""); // compile error, no method to call inside 'call' 
    return 0; 
} 
+1

不太清楚你想要达到的目标。在你的例子中,在编译时'const char *'没有重载,所以你得到那个编译错误。 –

+0

[这不是代码中唯一的错误。](http://coliru.stacked-crooked.com/a/6dc7e20197d5f898)这些调用'call'都不起作用,因为'impl'无法解析。 – WhozCraig

+0

此示例不起作用,没有上次调用的事件。我只描述了期望的行为。 – omicronns

回答

3

这是CRTP pattern几乎一个典型的例子,只是需要一些小的改动:

// A is now a template taking its subclass as a parameter 
template <class Subclass> 
class A { 
public: 
    template<typename ...tArgs> 
    void call(tArgs ...vArgs) { 
     for (int i = 0; i < 5; ++i) 
      // need to static cast to Subclass to expose impl method 
      static_cast<Subclass*>(this)->impl(vArgs...); 
    } 
}; 

// pass B into A template (the "curiously recurring" part) 
class B : public A<B> { 
public: 
    void impl() {} 
    void impl(int) {} 
}; 

int main() { 
    B b; 
    b.call(); // ok 
    b.call(1); // ok 
    // b.call(""); // will cause compile error, no method to call inside 'call' 
    return 0; 
} 
相关问题