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

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

最佳答案

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

f.template doIt<123>();

关于c++ - 当对象类型是模板参数时,有没有办法将模板参数传递给对象上的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12848010/

相关文章:

c++ - 模板被推断为模板变量的错误类型

c++ - 在类模板中定义一种本地类

function - Azure Function 处于只读模式

jquery - 从 $(document).ready(function()) 调用函数

c++ - OpenGL中动态模型的实例化绘制

c++ - 为什么我的 boost::spirit 规则不能编译用于解析列表列表?

c++ - boost::object_pool 是同步的吗?

c++ - static_cast const 引用 void*

c++ - 定义模板化静态类成员的不同实例化

function - 在 postgresql 中运行函数抛出运行时错误