简体   繁体   English

写一个只需要编译时常量参数的函数?

[英]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? 在C ++中,有没有一种方法可以编写一个函数,该函数可以将编译时常量作为参数,但是如果传递一个与运行时相关的值,则会产生编译错误? 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. 我知道一种方法是使用运行时检查所传递的参数是否为非空值,但我更希望在编译时捕获一般的原始指针转换(如果可能),并且仅允许当原始指针绝对为null时进行编译。

(Please be sure to mention if your technique depends on C++11 or C++14 features.) (请务必提及您的技术是否取决于C ++ 11或C ++ 14功能。)

Since C++11, you may use std::nullptr_t for what you want. 从C ++ 11开始,您可以根据需要使用std::nullptr_t

Demo . 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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