Why can't namespaces be template parameters?

强颜欢笑 提交于 2019-12-17 18:49:15

问题


I understand that namespaces cannot be template parameters. See the question, "template specialized on a namespace":

Given:

namespace A {
  class Foo;
  class Bar;
}

namespace B {
  class Foo;
  class Bar;
}

I want to template a class on the namespace A or B such that the following works:

template<name> class C {
  name::Foo* foo;
  name::Bar* bar;
};

I was wondering why this is the case. I understand that templates aren't structures, but is there a technical limitation to the compiler's design? Or is there some significant trade off for implementing this functionality?


回答1:


This would be:

  1. (IMO) Inappropriate: Namespaces avoid name clashes. Polymorphism is outside their charter.
  2. Unnecessary: It would achieve nothing that can't already be done with structs.
  3. Possibly difficult: A namespace isn't a complete, self-contained entity. Different members of a namespace can be declared in different headers and even different compilation units.



回答2:


Back when Bjarne Stroustrup first started talking about templates in C++ standards meetings he mentioned namespaces as template parameters. The reaction was skeptical, in part because namespaces themselves were so new, and we were afraid of combining two things that we didn't understand.



来源:https://stackoverflow.com/questions/12905951/why-cant-namespaces-be-template-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!