Mel*_*kon 6 c++ metaprogramming template-meta-programming
当我的一个ctors以编译时已知值调用时,我喜欢做一些检查.有没有办法检测它?
所以当有人称之为:
A a (10);
Run Code Online (Sandbox Code Playgroud)
因为10是一个已知的编译时间常数,所以我想调用一个特殊的ctor,如下所示:
template<int Value, typename = std::enable_if_t<Value <= 100>>
A (int Value) {}
Run Code Online (Sandbox Code Playgroud)
知道如何解决这个问题?谢谢!
积分常数可以解决您的问题:
struct A {
template<int v, std::enable_if_t<(v <= 100)>* = nullptr>
A(std::integral_constant<int, v>) {}
};
Run Code Online (Sandbox Code Playgroud)
然后,您可以像这样使用它:
A a{std:integral_constant<int, 7>{}};
Run Code Online (Sandbox Code Playgroud)
为了便于使用,您还可以使用类似的东西boost::hana。它定义了一个文字运算符,将数字转换为整数常量:
A a{76_c}; // the ""_c operator outputs an std::integral_constant<int, 76>
Run Code Online (Sandbox Code Playgroud)
您可以在boost::hana 文档中阅读有关此运算符的更多信息
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |