1

header.h

extern constexpr double sqrt_of_2;
extern constexpr double sqrt_of_1_2;
double sqrt(double x);

main.cpp

#include <header.h>

int main() {
  int n;
  scanf("%d", &n);
  printf("%lf %lf\n", sqrt_of_2, sqrt(n));
  return 0;
}

source.cpp

#include <header.h>

double sqrt(double x) {
 // complex bits of math
 // huge function
 // must not be in header for speedy compilation
 // will call other small non-constexpr functions in this file
}

constexpr double sqrt_of_2 = sqrt(2.0);
constexpr double sqrt_of_1_2 = sqrt(0.5)

This obviously does not work.

I can't add constexpr for sqrtin source.cpp because that will not match with declaration in header.h. I also can't add constexpr for sqrt in header.h because constexpr implies inline, I will then need to transfer everything in source.cpp to header.h.

Is this even possible?

1 Answer 1

3

No. That's the entire point of why constexpr was created -- to create functions to encapsulate compile-time functions.

It doesn't make sense to compile a compilation unit of code without the compile-time calculations done.

Object files are meant to simply be hooked up to resolve link-time dependencies. Compile-time computations must be defined at compile-time, and, therefore, must have an implementation in the compile-time unit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.