template <typename T>
class Predicate {
public:
bool operator()(const T& x) const;
};
template <typename T>
class LessThan : public Predicate<T> {
public:
explicit LessThan(const T& v) : val(v) {}
bool operator()(const T& x) const { return x < val; }
private:
const T val;
};
template <typename C, typename T>
class Producer {
public:
T operator()(const C& c) const;
};
template <typename C, typename V>
class HowMuch : public Producer<C, int> {
public:
explicit HowMuch(Predicate<V> p) : predicate{p} {}
int operator()(const C& c) const {
int count = 0;
for (const auto& x : c)
if (predicate(x)) ++count;
return count;
}
private:
Predicate<V> predicate;
};
int main() {
const LessThan<int> lf(5);
const HowMuch<list<int>, int> hm(lf);
list<int> li {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "How much numbers less than 5 is in {1, 2, 3, 4, 5, 6, 7, 8, 9, "
"10}? Answer: "
<< hm(li)
<< endl;
}
编译上述代码时,g++ 将其打印到控制台:
/tmp/ccblK6El.o: In function
HowMuch<std::__cxx11::list<int,
std::allocator<int> >, int>::operator()(std::__cxx11::list<int,
std::allocator<int> > const&) const
: templates.cpp:(.text._ZNK7HowMuchINSt7__cxx114listIiSaIiEEEiEclERKS3_[_ZNK7HowMuchINSt7__cxx114listIiSaIiEEEiEclERKS3_]+0x84): undefined reference toPredicate<int>::operator()(int const&) const
collect2: error: ld returned 1 exit status The terminal process terminated with exit code: 1
我不太明白 Prediate<V>
有什么问题里面的定义HowMuch
,因为对我(C++ 的新手)来说,它看起来真的很像 LGTM。根据我的理解,编译器创建了 Predicate<int>
的定义。作为一个单独的类型,并且日志准确地说明了这一点,但由于某种原因它找不到重载调用运算符的类型化定义。可能是类型推导的问题?容器模板类型本身的模板必须以某种方式显式定义?
编辑:
virtual
Predicate
都添加了修饰符的和Producer
的函数运算符重载,但问题似乎仍然存在。错误“描述”(如果它可以称为有用的描述)有点改变,但是(但它仍然指向相同的问题):
/tmp/ccn1Swqa.o: In function HowMuch >, int>::operator()(std::__cxx11::list > const&) const: templates.cpp:(.text._ZNK7HowMuchINSt7__cxx114listIiSaIiEEEiEclERKS3_[_ZNK7HowMuchINSt7__cxx114listIiSaIiEEEiEclERKS3_]+0x76): undefined reference to Predicate::operator()(int const&) const /tmp/ccn1Swqa.o:(.rodata._ZTV8ProducerINSt7__cxx114listIiSaIiEEEiE[_ZTV8ProducerINSt7__cxx114listIiSaIiEEEiE]+0x10): undefined reference to Producer >, int>::operator()(std::__cxx11::list > const&) const /tmp/ccn1Swqa.o:(.rodata._ZTV9PredicateIiE[_ZTV9PredicateIiE]+0x10): undefined reference to Predicate::operator()(int const&) const collect2: error: ld returned 1 exit status The terminal process terminated with exit code: 1
最佳答案
您需要为类的所有函数提供定义。这意味着即使您仅从 Predicate
派生类和 Producer
您仍然必须实现 operator()
在这些类(class)中。
如果您不想这样做(即只有函数声明而没有定义),请考虑通过声明 operator()
来使这两个类抽象方法纯虚拟。然后你不能直接从这些类实例化一个对象,而只能从实现 operator()
的派生类实例化一个对象。方法。这也意味着你只能通过 Predicate<V>*
在你的HowMuch
构造函数。
关于C++:未定义对仿函数重载调用运算符的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62057643/