Reputation: 347
I am new to Polymorphism and Templates in C++, and I came accross the error: "expression must have a constant value" when using the pointer of Dad
, what is the problem?
#include <iostream>
class Animal{
public:
std::string noise;
virtual void speak(char* message){
std::cout << message << " " << noise.c_str() << std::endl;
}
};
template <Animal* Parent> class Baby : public Animal{
public:
void speak(char* message){
std::cout << message << " " << Parent->noise.c_str() << Parent->noise.c_str() << std::endl;
}
};
int main(void){
Animal Dog;
Dog.noise = "WOOF";
Animal* Dad = &Dog;
Baby<Dad> puppy; // Error here
Dad->speak("I am a dog");
puppy.speak("I am a puppy");
return (0);
}
Wanted output:
I am a dog WOOF
I am a puppy WOOFWOOF
When I tried to run, I got the error: error C2971: 'Baby' : template parameter 'Parent' : 'Dad' : a local variable cannot be used as a non-type argument
Upvotes: 0
Views: 185
Reputation: 55887
You cannot use local pointer as template parameter, as sayed in message. You can use something like
class Animal{
public:
std::string noise;
void speak(char* message)
{
std::cout << message << " " << noise.c_str() << std::endl;
}
};
class Baby
{
public:
Baby(Animal* parent) : parent_(parent) {}
void speak(char* message)
{
std::cout << message << " " <<
parent->noise.c_str() << parent->noise.c_str() << std::endl;
}
private:
Animal* parent_;
};
and you do not need inheritance in this case.
Upvotes: 1