今天看書,Thinking in c++ volume 2 "Adaptable function objects"
里面作者說:
Suppose, for example, that we want to make the function object gt_n, defined
earlier in this chapter, adaptable. All we need to do is the following:class gt_n : public unary_function<int, bool> {
int value;
public:
gt_n(int val) : value(val) {}
bool operator()(int n) {
return n > value;
}
};
然后我做了一個template
#ifndef GREATERTHANN_HPP #define GREATERTHANN_HPP #include <functional> namespace ZJ { template <class ArgType, class Result = bool> struct gt_n : public std::unary_function<ArgType, Result> { private: ArgType value; public: gt_n(const ArgType& val) : value(val) {} Result operator()(ArgType n) { return (n > value); } ArgType getVal() { return value; } }; } #endif // GREATERTHANN_HPP
測試代碼:
//: C06:GreaterThanN.cpp #include "GreaterThanN.hpp" #include <iostream> #include <functional> #include <algorithm> using namespace ZJ; using namespace std; int main() { int a[] = { 10, 1, 2, 30, -10, -9, 3 }; const size_t SIZE = sizeof a / sizeof a[0]; gt_n<int> predicate(2); cout << "gt_n.getVal() = " << predicate.getVal() << endl; cout << count_if(a, a + SIZE, not1(predicate)) << endl; // 3 return 0; } ///:~
編譯時報錯
: error C3848: 具有類型“const ZJ::gt_n<int,bool>”的表達式會丟失一些 const-vola
tile 限定符以調用“bool ZJ::gt_n<int,bool>::operator ()(ArgType)”
with
[
ArgType=int
]
看起來大概意思是:你用的gt_n<int, bool>的instance具有const屬性,但是調用該instance的表達式(也就是“bool ZJ::gt_n<int,bool>::operator ()(ArgType))不具有const屬性,丟失const,所以無法通過編譯
最開始我在看main里面,predicate不具有const屬性啊
后來去查std::not1的文檔:http://en.cppreference.com/w/cpp/utility/functional/not1
template< class Predicate > std::unary_negate<Predicate> not1(const Predicate& pred);
因為std::not1用的是const Predicate&,所以我的predicate到not1之中以后就是const Predicate&了,所以在調用operator()的時候要求operator()也具有const屬性,否則就會導致丟失const限定符的錯誤
因此解決辦法就是給operator()加上const屬性,如下:
#ifndef GREATERTHANN_HPP #define GREATERTHANN_HPP #include <functional> namespace ZJ { template <class ArgType, class Result = bool> struct gt_n : public std::unary_function<ArgType, Result> { private: ArgType value; public: gt_n(const ArgType& val) : value(val) {} Result operator()(ArgType n) const { return (n > value); } ArgType getVal() { return value; } }; } #endif // GREATERTHANN_HPP
好了,現在可以通過編譯了。
你可以從上面std::not1文檔的Example代碼看出,operator()是加了const屬性的,因此這個地方是書的作者寫錯了。