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

SFINAE: Detecting if a function is called by a compile time known value

当我的一个 ctors 以编译时已知值被调用时,我喜欢做一些检查。有办法检测吗?

所以当有人这样称呼时:

A a (10);

因为 10 是一个编译时已知常数,我喜欢调用一个特殊的 ctor,像这样:

template<int Value, typename = std::enable_if_t<Value <= 100>>
A (int Value) {}

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

整数常量可以解决您的问题:

struct A {
    template<int v, std::enable_if_t<(v <= 100)>* = nullptr>
    A(std::integral_constant<int, v>) {}
};

那么,你可以这样使用它:

A a{std:integral_constant<int, 7>{}};

为了便于使用,您也可以使用类似于 boost::hana 的方法。它定义了一个将数字转换为整数常量的文字运算符:

A a{76_c}; // the ""_c operator outputs an std::integral_constant<int, 76>

您可以在 boost::hana documentation

中阅读有关此运算符的更多信息