标准或某些提升库是否提供编译时间变体?
我不是在问如何在编译时间期间,在给定索引上获取std ::变体成员的类型。
我询问标准或某些Boost库是否提供std :: variant
类似的类,其包含类型是在编译时已知的。
我相信,我要问的并不是完全胡说八道,因为有 boost :: hana ::可选
扮演相同角色(如我想象的类型),但相对于 std ::可选
。
至于其实用程序,它将允许一个人将几个过载写入一个,例如
void f(std::string, A);
void f(std::string, B);
void f(int, A);
void f(int, B);
可以清楚地写出实现,
void f(var<std::string, int>, var<A, B>);
如果constexpr 将用于输入类型上的分支。
I'm not asking how to Get type of a std::variant member at a given index during compile time.
I'm asking whether the standard or some boost library offer a std::variant
-like class whose contained type is known at compile time.
What I'm asking, I believe, is not completely nonsense, as there's boost::hana::optional
which plays the same role (as the type I'm imagining), but with respect to std::optional
.
As regards its utility, it would allow one to write several overloads into one, e.g.
void f(std::string, A);
void f(std::string, B);
void f(int, A);
void f(int, B);
could be written as
void f(var<std::string, int>, var<A, B>);
Clearly the implementation would make use of if constexpr
to branch on the input types.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C ++ 20概念和缩写模板功能以评论和Spencer的答案为基础,几乎可以为您提供所描述的内容。
https://godbolt.org/z/g5wdmtdgp
Building on the comments and Spencer's answer, C++20 concepts and abbreviated template functions will give you almost exactly what you described.
https://godbolt.org/z/G5WdMTdGP
您已经可以使用功能模板来实现既定目标。任何类型的变体都会不必要地使事物复杂化。您将在标题中的某个位置将特征类型类型:
然后,在实际的程序代码中,您将使用
One_of_V
模板来限制(通过C ++ 20函数约束)作为参数允许的类型:现在,
One_of
有点ham手,我可能会在真实代码中使用更多微妙的特质类型,但这正确演示了该概念。我亲自找到了
,如果constexpr
具有类型特征在减少模板功能所需的过载数方面非常有用。另外,它更简洁地解释了所有不同的情况,而彼此相邻,而不是以您无法一次理解的方式分散的过载功能。You can already accomplish your stated goal with a function template. Any type of variant would complicate things unnecessarily. You would have a traits type somewhere in a header:
And then, in your actual program code, you would use the
one_of_v
template to restrict (via a c++20 function constraint) the types allowed as parameters:Now,
one_of
is a bit ham-handed and I would probably use more subtle traits types in real code, but this demonstrates the concept correctly.I've personally found
if constexpr
with type traits very useful in reducing the number of overloads needed for template functions. Plus, it explains all the different cases more succinctly, all right next to each other, than overloaded functions that may be spread out in a way that you can't comprehend all at once.