【问题标题】:Pass a function as an explicit template parameter将函数作为显式模板参数传递
【发布时间】:2012-06-07 22:10:18
【问题描述】:

在下面的代码示例中,对foo 的调用有效,而对bar 的调用失败。

如果我注释掉对bar 的调用,代码会编译,这告诉我bar 的定义本身是可以的。那么如何正确调用bar呢?

#include <iostream>

using namespace std;

int multiply(int x, int y)
{
    return x * y;
}

template <class F>
void foo(int x, int y, F f)
{
    cout << f(x, y) << endl;
}

template <class F>
void bar(int x, int y)
{
    cout << F(x, y) << endl;
}

int main()
{
    foo(3, 4, multiply); // works
    bar<multiply>(3, 4); // fails

    return 0;
}

【问题讨论】:

标签: c++ templates


【解决方案1】:

这里的问题是,multiply 不是一个类型;它是一个,但函数模板bar 期望模板参数是一个类型。因此出现错误。

如果将函数模板定义为:

template <int (*F)(int,int)> //now it'll accept multiply (i.e value)
void bar(int x, int y)
{
    cout << F(x, y) << endl;
}

那么它就会起作用。见在线演示:http://ideone.com/qJrAe

您可以使用typedef 将语法简化为:

typedef int (*Fun)(int,int);

template <Fun F> //now it'll accept multiply (i.e value)
void bar(int x, int y)
{
    cout << F(x, y) << endl;
}

【讨论】:

    【解决方案2】:

    multiply 不是类型,而是函数。在这种情况下,它会衰减为函数指针。但是,bar 是为一个类型模板化的,而multiply 不是。

    Nawaz 已经反过来回答了这个问题(如何更改 bar 的定义以与函数一起使用),但是要回答您关于如何调用 bar 的明确问题,您需要一个合适的类型,像这样:

    struct Type {
      const int result;
      Type(int x, int y): result(x * y) {}
      operator int() const { return result; }
    };
    
    // usage
    bar<Type>(x, y);
    
    // (edit) a suitable type doesn't necessarily mean a new type; this works as well
    // if you aren't trying to solve any specific problem
    bar<std::string>(64, 64);
    

    【讨论】:

    • 如果他要使用这个,那么他也需要更改bar。语法F(x,y) 应该变成F(x,y)()
    • @Nawaz 不,Type 实际上并不是函子。它只是一个具有合适的构造函数和流输出重载的类型(在这种情况下,一个合适的转换运算符已经具有流输出重载)。 (见ideone.com/AgQGc
    • 哦..我忽略了...可能是因为函子在这里会是更好的选择,因此我期待着。
    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 2014-08-02
    • 2012-12-27
    • 2018-07-30
    相关资源
    最近更新 更多