【问题标题】:pass generic function to a template将泛型函数传递给模板
【发布时间】:2016-06-16 15:23:34
【问题描述】:

我有以下问题:

当我将一个模板函数传递给另一个模板函数时它不起作用,但是当我将一个普通函数传递给模板函数时它可以正常编译,例如:

template<class It, class Pred>
It findif(It begin,It end, Pred pr){
    while (begin!=end && !pr(*begin))
        begin++;
    return begin;
}
bool p(const string& s){
    /* some code */
}

当我将 p 传递给 findif 时,它不起作用:

template<class It, class Pred>
It findif(It begin,It end, Pred pr){
    while (begin!=end && !pr(*begin))
        begin++;
    return begin;
}
template<class T
bool p(const T& s){
    /* some code */
}

【问题讨论】:

  • 你是怎么通过的?你得到什么错误?
  • 很可能,您正在尝试将未实例化的模板传递给算法。你不能这样做,模板不是可调用的对象。 C++ 中也没有泛型函数。
  • @NathanOliver 我得到
  • 请考虑stackoverflow.com/help/mcve 以更快地获得更好的帮助。

标签: c++ templates


【解决方案1】:

模板函数是函数的蓝图,它们本身并不是函数。您必须实例化其中之一,以便编译器生成该特定实例。例如你不能这样做:

template<class It, class Pred>
It findif(It begin,It end, Pred pr) {
    while (begin!=end && !pr(*begin))
        begin++;
    return begin;
}

template<class T>
bool p(const T& s) {
    /* some code */
}

int main() {
  std::vector<int> v{1,2,3}; 
  findif(v.begin(), v.end(), p);
}

您必须首先实例化函数模板,代码才能被接受。也就是说,您必须为它提供明确的参数:

  findif(v.begin(), v.end(), p<int>);
                             ^^^^^^

【讨论】:

    【解决方案2】:

    如果您希望保留模板并仍然推断模板参数,则通常的方法是使用仿函数:

    struct p {
        template<class T>
        bool operator()(const T& s) const { /*...*/ }
    };
    
    // ...
    
    findif(v.begin(), v.end(), p{});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多