简体   繁体   中英

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

I like to do some check when one of my ctors are called with compile time known value. Is there a way to detect it?

So when someone call this:

A a (10);

since 10 is a compile time known constant, i like to call a special ctor, like this:

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

Any idea how can i solve this issue? Thanks!

Integral constant could solve your problem:

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

Then, you can use it like this:

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

For ease of use, you could also use something similar to what boost::hana does. It define a literal operator that transform the number into an integral constant:

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

You can read more about this operator in the boost::hana documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM