Per Andrei Alexandrescu's Modern C++ Design:
"The innate compile-time and combinatorial nature of templates makes them very attractive for creating design pieces. As soon as you try to implement such designs, you stumble upon several problems that not self-evident:
- You cannot specialize structure. Using templates alone, your cannot specialize the structure of a class (its data members). You can specialize only functions... "
At first I thought he meant you can't use template parameters in member variable declarations, as is done here:
class TestPolicy
{
std::string m_Name;
public:
std::string GetName() {return m_Name;}
void SetName(std::string name) {m_Name = name;}
};
template<typename Policy>
class PolicyUser
{
public:
Policy GetPolicy() {return m_Policy;}
void SetPolicy(Policy parg) {m_Policy = parg;}
private:
Policy m_Policy;
};
With the above definitions of TestPolicy and PolicyUser, a local TestPolicy variable can be instantiated and given to a local PolicyUser variable, like so:
int main(int argc, char** argv)
{
PolicyUser<TestPolicy> debug1;
TestPolicy t_Policy;
t_Policy.SetName("Groucho");
debug1.SetPolicy(t_Policy);
string mystring1 = debug1.GetPolicy().GetName();
cout << mystring1;
return 0;
}
And the output would be "Groucho". But for some reason the m_Name field can't be set by calling GetPolicy and then SetName, like this:
int main(int argc, char** argv)
{
PolicyUser<TestPolicy> debug1;
debug1.GetPolicy().SetName("Groucho");
string mystring1 = debug1.GetPolicy().GetName();
cout << mystring1;
return 0;
}
The output would be "". Nor can m_Name be set by doing this:
int main(int argc, char** argv)
{
PolicyUser<TestPolicy> debug1;
TestPolicy test;
debug1.SetPolicy(test);
debug1.GetPolicy().SetName("Groucho");
string mystring1 = debug1.GetPolicy().GetName();
cout << mystring1;
return 0;
}
Again, the output here would be "". So there seems to be a fuzzy rule about using template parameters to specialize data members. It seems to be possible but not very "neat". It could lead to confusion.
Can someone please explain:
-
Are there any use-cases or design patterns where template parameters are used to declare data members? If so, what are they? What are the dangers?
-
If not then why is it even possible to use the template parameter in the data member declaration?
Aucun commentaire:
Enregistrer un commentaire