问题
In my search for a way to store CRTP objects in a container, I found the following question:
A polymorphic collection of Curiously Recurring Template Pattern (CRTP) in C++?
I tryied the marked solution
https://stackoverflow.com/a/24795227/5475431
but the compiler is complainings erros like:
no known conversion for argument 1 from ‘std::shared_ptr<DerivedA>’ to ‘const std::shared_ptr<BaseInterface>&’
here is my try:
#include <vector>
#include <memory>
struct BaseInterface {
virtual ~BaseInterface() {}
virtual double interface() = 0;
};
template <typename Derived>
class Base : BaseInterface {
public:
double interface(){
return static_cast<Derived*>(this)->implementation();
}
};
class DerivedA : public Base<DerivedA>{
public:
double implementation(){ return 2.0;}
};
class DerivedB : public Base<DerivedB>{
public:
double implementation(){ return 1.0;}
};
int main() {
std::vector<std::shared_ptr<BaseInterface>> ar;
ar.emplace_back(std::make_shared<DerivedA>());
return 0;
}
do you have any idea how to fix the compiler error, or how to solve the problem better? Thanks in advance
回答1:
Base
should be an public inheritance of BaseInterface
(and you also forgot return
).
Then ar.emplace_back(std::make_shared<DerivedA>());
well works:
DEMO
template <typename Derived>
class Base : public BaseInterface {
public:
double interface(){
return static_cast<Derived*>(this)->implementation();
}
};
回答2:
You're missing a return statement and Base
should inherit from BaseInterface
publically.
template <typename Derived>
struct Base : BaseInterface
{
double interface() {
return static_cast<Derived*>(this)->implementation();
}
};
Live demo
But beware https://stackoverflow.com/a/24795059/5470596 <-- the answer the other OP should have accepted.
来源:https://stackoverflow.com/questions/54654770/c-vector-of-crtp-shared-pointers