- 论坛徽章:
- 0
|
问题:
我写了一个模板,需要一个函数指针作为模板差数,但是特例化时,向其传入一个函数名的时候却出现了如下的错误:
'...'cannot appear in a constant-expression
代码如下:
- #include <vector>
- #include <iterator>
- template <typename T, bool (*compare)(const T&,const T&)>
- class Base
- {
- public:
- int search(const T& in, T* out );
- private:
- std::vector<T> elems;
- };
- template <typename T, bool (*compare)(const T&,const T&)>
- int Base<T,compare>::search(const T& in, T* out)
- {
- std::vector<T>::iterator iter;
- for(iter = elems.begin() ; iter < elems.end(); iter++ )
- {
- if( *compare(*iter,in) )
- {
- out = iter;
- }
- }
- }
- class CashMgr{
- public:
- bool compare(const int & item1,const int & item2);
- private:
- Base<int,compare> x;
- };
- bool CashMgr::compare(const int & item1,const int & item2)
- {
- if(item1 == item2) return true;
- }
复制代码
编译结果如下:
- [who@Test]$ g++ -g testTemplate_funcPointer.cpp
- testTemplate_funcPointer.cpp: In member function `int Base<T, compare>::search(const T&, T*)':
- testTemplate_funcPointer.cpp:15: error: expected `;' before "iter"
- testTemplate_funcPointer.cpp:17: error: `iter' was not declared in this scope
- testTemplate_funcPointer.cpp: At global scope:
- testTemplate_funcPointer.cpp:30: error: `bool CashMgr::compare(const int&, const int&)' cannot appear in a constant-expression
- testTemplate_funcPointer.cpp:30: error: template argument 2 is invalid
- testTemplate_funcPointer.cpp:30: error: ISO C++ forbids declaration of `x' with no type
复制代码
另外,这样的定义怎么也错了呢?
- std::vector<T>::iterator iter;
复制代码 |
|