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

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

So when someone calls it:

A a (10); 

since 10 is a well-known compile-time constant, I like to call a special ctor, for example:

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

Any idea how I can solve this problem? Thanks!

+6
source share
1 answer

Integral constant can 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 as follows:

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

For ease of use, you can also use something similar to what boost::hana does. It defines a literal operator that converts a number to an integral constant:

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

You can learn more about this statement in boost :: hana documentation

+4
source

Source: https://habr.com/ru/post/1013196/


All Articles