[英]Member detection based on custom void_t implementation
I've got the book C++ Templates the complete guide and I'm trying to implement some of the described techniques.我已经拿到了 C++ 模板一书的完整指南,我正在尝试实现一些描述的技术。 One of these is member function detection, but my implementation seems not working.
其中之一是成员函数检测,但我的实现似乎不起作用。
I can't use void_t as I'm using C++11, but I copied the definition, so this should be not the problem.我不能使用 void_t,因为我使用的是 C++11,但我复制了定义,所以这应该不是问题。
Following is the code:以下是代码:
namespace nt_detail
{
template< class... >
using void_t = void;
}
template<typename T, typename = nt_detail::void_t<>>
struct HasHelloMember
: std::false_type {};
template<typename T>
struct HasHelloMember<T,
nt_detail::void_t<decltype(std::declval<T>().hello())>>
: std::true_type {};
and here the test one:这里是测试一:
class ZZZ
{
};
class ZZZ2
{
public:
void hello()
{}
};
int main()
{
if(HasHelloMember<ZZZ>::value)
{
std::cout << "ZZZ has hello" << std::endl;
}
else
{
std::cout << "ZZZ has NOT hello" << std::endl;
}
if(HasHelloMember<ZZZ2>::value)
{
std::cout << "ZZZ2 has hello" << std::endl;
}
else
{
std::cout << "ZZZ2 has NOT hello" << std::endl;
}
}
In both cases I get "has hello".在这两种情况下,我都会得到“你好”。 Is there something wrong with my void_t implementation perhaps?
我的 void_t 实现可能有问题吗?
Try this definition of void_t
unless You are using C++17:试试这个
void_t
定义,除非你使用的是 C++17:
template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
According to https://en.cppreference.com/w/cpp/types/void_t :根据https://en.cppreference.com/w/cpp/types/void_t :
Until CWG 1558 (a C++14 defect), unused parameters in alias templates were not guaranteed to ensure SFINAE and could be ignored, so earlier compilers require a more complex definition of void_t, such as
在 CWG 1558(C++14 缺陷)之前,别名模板中未使用的参数不能保证确保 SFINAE 并且可以被忽略,因此早期的编译器需要更复杂的 void_t 定义,例如
This is an issue with gcc until version 5.1.在 5.1 版之前,这是 gcc 的一个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.