当对象类型是模板参数时,有没有办法将模板参数传递给对象上的函数?

时间:2011-09-22 09:03:37

标签: c++ templates function arguments c++11

举例说明:

struct MyFunc {

    template <size_t N>
    void doIt() {
        cout << N << endl;
    }

};

template <typename Func>
struct Pass123ToTemplateFunc {

    static void pass(Func f) {
        f.doIt<123>(); // <-- Error on compile; is there a way to express this?
    }

};

int main() {

    Pass123ToTemplateFunc<MyFunc>::pass(MyFunc());

    return 0;

}

这纯粹是语法好奇心;是否有一种方法可以在语言中表达这一点而不将参数传递给doIt函数本身?如果没有,这没什么大不了的,我已经很清楚我可以优雅地解决它的方式,所以不需要提供替代解决方案。 (我接受&#34;没有&#34;作为答案,换句话说,如果这是真理。:-P)

1 个答案:

答案 0 :(得分:8)

您必须告诉编译器doIt将是一个模板:

f.template doIt<123>();