当对象类型是模板参数时,有没有办法将模板参数传递给对象上的函数? [英] Is there a way to pass template arguments to a function on an object when the object type is a template argument?

查看:16
本文介绍了当对象类型是模板参数时,有没有办法将模板参数传递给对象上的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举例说明:

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 函数本身的情况下表达这一点?如果没有,这没什么大不了的,我已经很清楚我可以优雅地解决它的方法,因此无需提供替代解决方案.(我会接受不"作为答案,换句话说,如果这是事实的话.:-P)

This is pretty much purely a syntax curiosity; is there a way in the language to express this without passing arguments to the doIt function itself? If not, it's no big deal and I'm already well aware of ways I can gracefully work around it, so no need to provide alternative solutions. (I'll accept "no" as an answer, in other words, if that's the truth. :-P)

推荐答案

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

You have to tell the compiler that doIt will be a template:

f.template doIt<123>();

这篇关于当对象类型是模板参数时,有没有办法将模板参数传递给对象上的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆