是否可以将模板实例视为命名空间?
假设我从
template< unsigned int num >
class SomeFunctionality
{
static unsigned int DoSomething()
{
//...
}
static void DoSomethingElse()
{
}
};
typedef SomeFunctionality<6> SomeFunctionalityFor6;
语义上讲,“SomeFunctionalityFor6”本质上是特定于模板参数 6 的命名空间。因此,在使用模板实例的代码中,
int main()
{
SomeFunctionalityFor6::DoSomething();
}
我宁愿能够使用“using”语句,例如真正的 我怀疑
int main()
{
using SomeFunctionalityFor6;
DoSomething();
}
这不起作用。 Visual Studio 抱怨它需要一个由任何 using 语句后面的“namespace”关键字定义的命名空间。
有什么办法可以做我想做的事吗? 主要是我不想每次调用静态方法时都完全限定名称空间。 我知道它主要只是语法糖,但在我看来它可以使代码更具可读性。 我想知道是否有直接模板化命名空间的方法,而不必使用“class”关键字。
Suppose I have
template< unsigned int num >
class SomeFunctionality
{
static unsigned int DoSomething()
{
//...
}
static void DoSomethingElse()
{
}
};
typedef SomeFunctionality<6> SomeFunctionalityFor6;
Semantically, "SomeFunctionalityFor6" is essentially a namespace specific to the template argument, 6. So in the code using this instance of the template instead of doing
int main()
{
SomeFunctionalityFor6::DoSomething();
}
I'd rather have the ability to use a "using" statement ala a real namespace
int main()
{
using SomeFunctionalityFor6;
DoSomething();
}
This, as I would suspect doesn't work. Visual studio complains that it wants a namespace defined by the "namespace" keyword following any using statement.
Is there anyway to do what I'm trying to do? Mainly I just don't want to fully qualify the namespace everytime I call the static methods. I know its mostly just syntactic sugar, but in my opinion it can make code much more readable. I'm wondering if there's even ways to templatize a namespace directly instead of having to use the "class" keyword.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能那样做。 既不模板化命名空间,也不使用 class_name。
代码中唯一可以在没有限定的情况下使用类中的静态函数的地方是派生类。
在你的情况下,我会使用 typedef 来表示一些短名称,例如
You can't do that. Neither templatized namespace, nor using class_name.
The only places in the code that can use static functions from a class without qualification are derived classes.
In your case, I would use a typedef for some short name, like
或者您可以只创建一个本地对象...
您可以随意替换/更改 SF6 对象。
Or you could just create a local object...
You could replace/change the SF6 object at will.