C++ sfinae是否实例化了一个函数体?
我想使用通常的SFINAE技巧检测类的特定成员函数的存在C++ sfinae是否实例化了一个函数体?,c++,templates,sfinae,C++,Templates,Sfinae,我想使用通常的SFINAE技巧检测类的特定成员函数的存在 template<typename T> struct has_alloc { template<typename U,U x> struct dummy; template<typename U> static char test(dummy<void* (U::*)(std::size_t),&U::allocate>*); templa
template<typename T>
struct has_alloc
{
template<typename U,U x>
struct dummy;
template<typename U>
static char test(dummy<void* (U::*)(std::size_t),&U::allocate>*);
template<typename U>
static char (&test(...))[2];
static bool const value = sizeof(test<T>(0)) ==1;
};
我正在检查测试是否是我要找的
struct kind_of_alloc
{
const static bool value = has_alloc<test_alloc>::value;
};
在另一个编译单元中。但是,当has_alloc测试发生时,编译器尝试实例化std::allocator的allocate函数,发现函数体中使用了不完整类型的sizeof,并导致一个硬错误。
如果allocate的实现在诸如
template<typename T>
T* alloc<T>::allocate(std::size_t n)
{
return (T*)operator new(sizeof(T)*n);
}
void use()
{
test_alloc a;
a.allocate(2);
}
但是,虽然我可以为alloc
执行此操作,但是对于std::allocator
来说是不可能的,因为分离实现是不可能的。
我所寻找的是可以测试
test\u alloc
中是否存在带有void*allocate(size\u t)
的函数。如果不是,它将测试为阴性,如果是,即如果函数签名匹配,即使不能在那里实例化,也将测试为阳性 否,SFINAE仅在过载解决期间有效。一旦解决了问题,编译器开始实例化函数SFINAE,就结束了
编辑:并获取函数的地址来实例化它。那么,是否可以以任何其他方式编写测试函数,使其与函数的地址不匹配,从而不实例化函数?
#include "test_def.hpp"//contains the code posted above
struct test{};
void use()
{
test_alloc a;
}
template<typename T>
T* alloc<T>::allocate(std::size_t n)
{
return (T*)operator new(sizeof(T)*n);
}
void use()
{
test_alloc a;
a.allocate(2);
}
template<typename T>
struct alloc
{
T* allocate(std::size_t n);
};