“模板化"命名空间

编程入门 行业动态 更新时间:2024-10-24 01:57:17
本文介绍了“模板化"命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想构建这样的东西:

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.

更多推荐

“模板化"命名空间

本文发布于:2023-11-09 06:01:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   空间   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!