SFINAE:检测函数是否由编译时已知值调用

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)

知道如何解决这个问题?谢谢!

Gui*_*cot 4

积分常数可以解决您的问题:

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 文档中阅读有关此运算符的更多信息

  • 这实际上是一个非常好的解决方案,+1,其余 99% 的 C++ 程序员应该了解 `integral_constant` :) 如果您想要简单地在编译时测试某些常量的值,我肯定会走这条路。 (4认同)