为什么成员函数不能用作模板参数? [英] Why member functions can't be used as template arguments?
问题描述
为什么成员函数不能用作模板参数?例如,我想这样做:
Why member functions cannot be used as template arguments? For example, I want to do like:
struct Foo {
void Bar() { // do something
}
};
template <typename TOwner, void(&func)()>
void Call(TOwner *p) {
p->func();
}
int main() {
Foo a;
Call<Foo, Foo::Bar>(&a);
return 0;
}
我知道可以使用指向成员的指针来完成类似的事情;好吧,大多数时候它已经足够酷了,但我只是好奇为什么应该"使用指针.
I know that a similar thing can be done using pointers-to-member; well, it's cool enough most of the time, but I'm just curious about why pointers "should" be used.
我认为解释上面的p->func()"没有歧义.为什么标准禁止我们使用成员函数作为模板参数?根据我的编译器(VC++ 2013),甚至不允许使用静态成员函数.有谁知道原因?或者,有没有办法在不因指针取消引用而损失任何性能的情况下做同样的事情?
I see no ambiguity of interpreting "p->func()" above. Why the standard prohibits us to use member functions as template arguments? Even static member functions are not allowed according to my compiler (VC++ 2013). Does anyone know the reason? Or, is there a way to do the same thing without loss of any performance due to pointer dereferencing?
谢谢.
推荐答案
它们可以用作非类型参数,但需要使用正确的语法
They can be used as non-type parameters, but you need to use the right syntax
struct Foo {
void Bar() { // do something
}
};
template <typename TOwner, void(TOwner::*func)()>
void Call(TOwner *p) {
(p->*func)();
}
int main() {
Foo a;
Call<Foo, &Foo::Bar>(&a);
return 0;
}
这篇关于为什么成员函数不能用作模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!