【发布时间】:2018-10-09 15:41:26
【问题描述】:
如果我有一个两个模板的基类和一个派生类:
template <typename T>
class Base {
public:
typedef T (*func)();
Base(func f):m_f(f){};
T invoke(){ return m_f();};
private:
func m_f;
};
template <typename D>
class Derived : public Base<D> {
public:
Derived(Base<D>::func f) : Base<D>(f) { };
D foo() {
return Base<D>::invoke();
}
};
派生类需要将函数指针传递给Ctor中的基类。看完Inheritance and templates in C++ - why are methods invisible?我明白了,应该按如下方式调用Ctor中的typedef:
Derived(Base<D>::func f) : Base<D>(f) {};
但是,当我尝试编译时:
int returnZero(){
return 0;
}
Derived<int> d(returnZero);
std::cout << d.foo() << std::endl;
我明白了:
error: expected ')' before 'f'
Derived(Base<D>::func f) : Base<D>(f) { };
^
cpp_code.cpp: In function 'int main()':
cpp_code.cpp:59:27: error: no matching function for call to 'Derived<int>::Derived(int (&)())'
Derived<int> d(returnZero);
^
cpp_code.cpp:47:7: note: candidate: constexpr Derived<int>::Derived(const Derived<int>&)
class Derived : public Base<D> {
^~~~~~~
cpp_code.cpp:47:7: note: no known conversion for argument 1 from 'int()' to 'const Derived<int>&'
cpp_code.cpp:47:7: note: candidate: constexpr Derived<int>::Derived(Derived<int>&&)
cpp_code.cpp:47:7: note: no known conversion for argument 1 from 'int()' to 'Derived<int>&&'
在Ctor中使用函数指针(func)的正确方法是什么?
【问题讨论】:
标签: c++ templates inheritance