[英]Check for the existence of a global(/namespaced) function/object declaration
C++11 allows to check, reasonably concisely, for the existence of a member: Is it possible to write a template to check for a function's existence? C ++ 11允许合理地简明地检查成员是否存在: 是否可以编写模板来检查函数的存在?
Is it possible to check for the existence of a global function declaration (namespaced or not)? 是否可以检查是否存在全局函数声明(是否为命名空间)?
Details: In my particular case, I'd like to check if my stdio.h implementation ( #include
d) defines eg, fprintf_unlocked
(with the standard signature) and use that if it does, otherwise default to fprintf
. 详细信息:在我的特定情况下,我想检查我的stdio.h实现(
#include
d)是否定义了例如fprintf_unlocked
(带有标准签名)并使用它(如果有),否则默认为fprintf
。
A way to check existence of function, You may create following traits: 检查函数是否存在的方法,您可以创建以下特征:
#define DEFINE_HAS_SIGNATURE(traitsName, funcName, signature) \
template <typename U> \
class traitsName \
{ \
private: \
template<typename T, T> struct helper; \
template<typename T> \
static std::uint8_t check(helper<signature, &funcName>*); \
template<typename T> static std::uint16_t check(...); \
public: \
static \
constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t); \
}
DEFINE_HAS_SIGNATURE(has_foo, foo, T*);
DEFINE_HAS_SIGNATURE(has_bar, bar, T*);
And then test it 然后测试一下
has_foo<void(int)>::value
I've made a hybrid traits generator macro that checks for either members or free standing functions. 我已经制作了一个混合特征生成器宏来检查成员或独立功能。
This creates template traits classes that look whether a user supplied signature (first template arg) works with the name embedded in the traits class. 这将创建模板特征类,以查看用户提供的签名(第一个模板arg)是否与traits类中嵌入的名称一起使用。
It looks for free-standing names if no second template param is supplied ( Trait<Sig>::value
), or for a member of the second template argument if the traits template is instantiated with two arguments ( Trait<Sig,ClassToSearch>::value
). 如果没有提供第二个模板参数(
Trait<Sig>::value
),则查找独立名称;如果使用两个参数( Trait<Sig,ClassToSearch>::value
实例化traits模板,则查找第二个模板参数的成员) Trait<Sig,ClassToSearch>::value
)。
It can only search for free functions that were declared before the Traits template class was defined. 它只能搜索在定义Traits模板类之前声明的自由函数。
#define DEF_HAS_SIG(TraitsName, funcName) \
std::nullptr_t funcName(...); \
template<typename Sig, typename Type=void> class TraitsName { \
typedef char yes[1]; \
typedef char no [2]; \
template <typename U, U> struct TypeCheck; \
template <typename _1, typename _2 > static no &chk(...); \
template <typename _1, typename _2> static \
typename std::enable_if< std::is_same<void,_2>::value, yes&>::type chk(TypeCheck<_1, &funcName > *); \
template <typename _1, typename _2> static yes& chk(TypeCheck<_1, &_2::funcName > *); \
public: static bool const value = sizeof(chk<Sig,Type>(0)) == sizeof(yes); \
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.