Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile time checking of constness

If I have a function

int calcStuff_dynamic(const int a, const int b)

and some template meta code

template<int a, int b>
struct calcStuff_static {
    static const int value = //some more code
};

Is there a way to write a wrapper

int calcStuff(const int a, const int b) {
    IF_THESE_ARE_KNOWN_CONSTANTS_AT_COMPILE_TIME(a, b)
        return calcStuff_static<a, b>::value;
    ELSE_TEMPLATE_WOULD_FAIL
        return calcStuff_dynamic(a, b);
}
like image 556
user315118 Avatar asked Nov 10 '22 05:11

user315118


1 Answers

You can not do it, but it will be done by smart compilers.

Maybe first solution that comes to the mind is to use SFINAE in combination of constexpr values. In this case we need something to detect constexpr values.

But, there is no is_constexpr or something similar to detect values that are known in compile time. On the other hand, the function is_const is not useful because constexpr is not part of a type. So, you can not do that (or at least I don't know a straight solution).

However you will be glad if you know that there is an optimization is many compilers which computes the final value of a function for known values in compile time. For example in GCC, there is "SCEV final value replacement".

Therefore you should just use that dynamic function when the parameters are unknown and the compiler will do it as your wish (If it is possible).

like image 68
masoud Avatar answered Nov 15 '22 06:11

masoud