Eva*_*ran 15 c++ templates functor
考虑这个简单而毫无意义的代码.
#include <iostream>
struct A {
template<int N>
void test() {
std::cout << N << std::endl;
}
};
int main() {
A a;
a.test<1>();
}
Run Code Online (Sandbox Code Playgroud)
这是一个非常简单的函数模板示例.但是,如果我想A::test
用重载代替operator()
它以使它成为一个算符呢?
#include <iostream>
struct A {
template<int N>
void operator()() {
std::cout << N << std::endl;
}
};
int main() {
A a;
a<1>(); // <-- error, how do I do this?
}
Run Code Online (Sandbox Code Playgroud)
当然,如果采用operator()
依赖于模板的参数,编译器可能会推导出模板.但我无法弄清楚使用无参数仿函数指定模板参数的正确语法.
有没有正确的方法来做到这一点?
显然,这个代码可以工作,因为它绕过了仿函数语法:
a.operator()<1>();
Run Code Online (Sandbox Code Playgroud)
但这有点打败了它作为仿函数的目的:-P.
lot*_*har 26
你只能打电话
a.operator()<1>();
Run Code Online (Sandbox Code Playgroud)
但那不会使用仿函数.函数需要一个非模板运算符(),因为它们必须能够被称为varname(),并且不能与您的代码一起使用.
要使它成为一个真正的仿函数,请将代码更改为模板类(仿函数是类):
#include <iostream>
template<int N>
struct A {
void operator()() {
std::cout << N << std::endl;
}
};
int main() {
A<1> a;
a();
}
Run Code Online (Sandbox Code Playgroud)
Tod*_*ner 10
除了以下之外,我不知道另一种"直接"的方式:
a.operator()<1>();
Run Code Online (Sandbox Code Playgroud)
句法.如果你愿意改变代码,那么将模板参数移动到类就可以了,或者使用(boost | tr1):: bind来创建一个(boost | tr1):: function对象.