当对象类型是模板参数时,有没有办法将模板参数传递给对象上的函数?
问题描述:
举例说明:
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>();