2

Say I have two templated classes, one pure virtual parent and another that inherits from the parent. Both are templated to take a generic type and a functor. For example:

template<typename T, typename funct>
class pure_virtual{
     //pure virtual members
}
template<typename T, typename funct>
class child : public pure_virtual{
     //members
}

In my main, I want to create a pure_virtual pointer to my child class without the use of dynamic memory. For example:

int main(){
     pure_virtual<int*,my_functor>* p;
     child<int*,my_functor> c(my_functor);
     p = &c;
     return 0;
}

This implementation gives me a compile error stating that it cannot convert type child into type pure_virtual. Any idea as to what I'm doing wrong here? I know if I use dynamic allocation, this will work; however, I would really like to avoid it if possible.

Thanks

4

3 回答 3

3

You have fallen victim to a vexing parse. child<int*,my_functor> c(my_functor) does not declare a child<int*,my_functor> object, but instead declares a function which takes a my_functor and returns a child<int*,my_functor>.

Such a function cannot be converted in to a pure_virtual<int*,my_functor>*.

To fix this, change that line to:

child<int*,my_functor> c((my_functor()));
于 2013-02-23T05:28:26.423 回答
1

1)

class child : public pure_virtual< T, funct> {
...

2)

child< int*,my_functor > c(my_functor);

If my_functor is a type, then you can't pass it to c-tor.

于 2013-02-23T05:26:54.443 回答
1

Here is a compilable example:

template<typename T, typename funct>
class pure_virtual{
     //pure virtual members
};

template<typename T, typename funct>
class child : public pure_virtual<T,funct> {
  public:
     //members
     child(funct) { }
};

struct my_functor {};

int main(){
     pure_virtual<int*,my_functor>* p;
     my_functor f;
     child<int*,my_functor> c(f);
     p = &c;
     return 0;
}
于 2013-02-23T05:28:47.333 回答