“模板化"命名空间 [英] "templating" a namespace

查看:91
本文介绍了“模板化"命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建这样的东西:

File 1:
template<typename Vector>
namespace myNamespace {
  class myClass1{ myClass1(Vector v) {...} }
}

File 2:
template<typename Vector>
namespace myNamespace {
  class myClass2{ myClass2(Vector v) {...} }
}

这当然是不可能的,因为您无法模板化名称空间. 取而代之的是,我可以使用结构而不是名称空间,但是之后,我无法将名称空间功能分散到多个文件中.

Of course this is not possible because you cannot template namespaces. Instead I could use a struct instead of a namespace, but then I cannot spread the namespace functions over several files.

有没有解决这种问题的方法?

Is there any solution for such a problem?

PS:我知道我可以对类进行模板化,但是随后我必须在创建新类时指定要使用的向量类型.

PS: I know I could template the classes, but then I'd have to specify which vector type I want to use anytime I create a new class.

推荐答案

关注您的评论:

代替写作

using namespace myNamespace<int>;

只需使用模板化的类并编写该类(或任何其他变体)即可:

Just use templated classes and write this instead (or whatever variation):

typedef myNamespace::myClass1<int> myClass1Int;
typedef myNamespace::myClass2<int> myClass2Int;

我倾向于认为,最好是明确说明正在使用的类型,而不是尝试执行诸如导入名称空间的特定实例之类的事情.

I tend to think it's better to be explicit about what types are being used rather than trying to do something like import a particular instantiation of a namespace.

您能否更全面地描述使模板名称空间有用的问题?

Can you more fully describe the problem that makes you think templated namespaces would be useful?

请记住,您始终可以编写一个make_myClass1自由函数来为您推断模板类型.

And remember you can always write a make_myClass1 free function to deduce the template type for you.

这篇关于“模板化"命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆