If constexpr (condition) as compilation conditional

I want to use constexpr bool ( useF

in the example below) to include a function in the following code. Called here A::f()

. Also, I want the alias template ( a

) to be void

in case of a function disable.

I tried using the constexpr if statement, but the body is still being generated, causing a compilation error. If I use the shell ( X

) pattern , the body is discarded as I expected, but this seems ugly to me. Are there any other ways to do this?

constexpr bool useF = false;

struct A {
    static void f() {}
};

using a = std::conditional<useF, A, void>::type;

template<typename L>
struct X {
    static void h() {
        if constexpr(std::is_same<L, A>::value) {
            L::f(); // not instantiated, no error
        }
    }
};

int main() {
    if constexpr(useF) {
        a::f(); // error!?
    }

    X<a>::h();
}

      

I am using g ++ - 7.0.1 with -std = c ++ 17

+3


source to share


1 answer


if constexpr

is for templates only. From [stmt.if]:

If the operator if

has the form if constexpr

, the value of the condition must be a context-transformed constant expression of type bool

(5.20); this form is called a constexpr if statement. If the value is a transformed condition false

, the first subtask is a discarded statement, otherwise the second subordination, if present, is a discarded statement. During the creation of a private template (Section 14) , if the condition does not depend on the value after its creation, the discarded subtask (if any) is not created.



Internally, X

a constexpr if statement will prevent the creation of an otherwise incorrectly instantiated instance. This is the purpose of this language function. But outside of templates, there is no such equivalent gain.

+4


source







All Articles