简体   繁体   中英

Writing a function which only takes compile-time constant parameters?

Is there a way in C++ to write a function which can take a compile-time constant as a parameter, but will give a compilation error if you pass a value which is run time dependent? Specifically, I have a constructor where initializing with a null pointer would have an acceptable behavior, but where initializing with a non-null pointer means that something funky is going on.

Details, if they matter: the class can be constructed with a smart pointer, but shouldn't be constructed from a (non-null) raw pointer. For brevity, I'd like to be able to initialize directly from a null pointer literal, but the smart pointer disallows implicit conversions from raw pointers. This means there's extra verbiage needed at each point of use to explicitly wrap the null pointer in a smart pointer. It would be nice to de-duplicate code by moving the wrapping into the constructor.

I know that one way to do this is to use a run-time check on if the passed parameter is non-null, but I'd much prefer to have general raw pointer conversion caught at compile-time, if possible, and only allowing compilation when the raw pointer is definitely null.

(Please be sure to mention if your technique depends on C++11 or C++14 features.)

Since C++11, you may use std::nullptr_t for what you want.

Demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM