Why can function pointers be `constexpr`?

前端 未结 4 2044
花落未央
花落未央 2021-02-03 22:31

How does the compiler know where in memory the square root will be before the program is executed? I thought the address would be different everytime the program is executed, bu

4条回答
  •  独厮守ぢ
    2021-02-03 23:06

    At compile time, the compiler doesn't know the address of sqrt. However, you cannot do anything at compile time with a constexpr function pointer that would allow you to access that pointer's address. Therefore, a function pointer at compile time can be treated as an opaque value.

    And since you can't change a constexpr variable after it has been initialized, every constexpr function pointer can be boiled down to the location of a specific function.

    If you did something like this:

    using fptr = float(*)(float);
    
    constexpr fptr get_func(int x)
    {
      return x == 3 ? &sqrtf : &sinf;
    }
    
    constexpr fptr ptr = get_func(12);
    

    The compiler can detect exactly which function get_func will return for any particular compile time value. So get_func(12) reduces down to &sinf. So whatever &sinf would compile to is exactly what get_func(12) would compile to.

提交回复
热议问题