c ++函子和函数模板 [英] c++ functor and function templates

查看:147
本文介绍了c ++函子和函数模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个简单和无意义的代码。

consider this simple and pointless code.

#include <iostream>

struct A {
    template<int N>
    void test() {
    	std::cout << N << std::endl;
    }
};

int main() {
    A a;
    a.test<1>();
}

这是一个非常简单的函数模板示例。然而,如果我想用重载的运算符()替换 A :: test 以使其成为函子?

It is a very simple example of a function template. What if however, I wanted to replace A::test with an overloaded operator() to make it a functor?

#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?
}

当然,如果 $ c>参数取决于模板,编译器可能推断出模板。但是我只是无法找出合适的语法来使用无参数函数指定模板参数。

Certainly if the operator() took parameters which were dependent on the template, the compiler could possibly deduce the template. But I just can't figure out the proper syntax to specify template parameters with a parameterless functor.

有正确的方法吗? >

Is there a proper way to do this?

显然,这段代码可以工作,因为它绕过了functor语法:

Obviously, this code would work since it bypasses the functor syntax:

a.operator()<1>();

但是这样做会失去它作为函子的目的:-P。

but that kinda defeats the purpose of it being a functor :-P.

推荐答案

除了:

 a.operator()<1>();

语法。如果你打算更改代码,将模板参数移动到类将工作,或使用(boost | tr1)::绑定,使(boost | tr1)::函数对象。

syntax. If you're open to changing the code, moving the template parameter to the class would work, or using a (boost|tr1)::bind to make a (boost|tr1)::function object.

这篇关于c ++函子和函数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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