【问题标题】:Create a class method template, that will use function implemented later创建一个类方法模板,该模板将使用稍后实现的功能
【发布时间】:2017-04-05 17:14:58
【问题描述】:

是否有可能实现这样的行为?它不必使用继承,我只想通过泛型参数传递(使用 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;
}

【问题讨论】:

  • 不太清楚你想要实现什么。在您的示例中,const char* 在编译时没有重载,因此您会收到编译错误。
  • That's not the only error in that code. 这些对call 的调用都不起作用,因为impl 无法解析。
  • 这个例子不起作用,没有最后一次调用的事件。我只描述了期望的行为。

标签: c++ templates template-method-pattern


【解决方案1】:

这几乎是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;
}

【讨论】:

    猜你喜欢
    • 2016-10-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多