2017-02-26 8 views
1

header.h가비 constexpr 기능 constexpr 변수를 설정 (그러나 컴파일시에 연산 할 수있다)을

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) 

이것은 분명히 작동하지 않습니다.

source.cpp에 sqrtconstexpr을 추가 할 수 없습니다. header.h의 선언과 일치하지 않기 때문입니다. constexprinline이 포함되어 있기 때문에 header.h에 sqrt에 대해 constexpr을 추가 할 수 없기 때문에 모든 것을 source.cpp에서 header.h로 전송해야합니다.

이것도 가능합니까?

답변

3

아니요. constexpr이 만들어진 이유의 요점은 컴파일 타임 기능을 캡슐화하는 기능을 만드는 것입니다.

컴파일 타임 계산을 수행하지 않고 컴파일 단위를 컴파일하는 것은 의미가 없습니다.

개체 파일은 링크 시간 종속성을 해결하기 위해 간단하게 연결됩니다. 컴파일 타임 계산은 컴파일시 정의되어야하며, 따라서 컴파일 타임 단위로 구현되어야합니다.