使用SFINAE检测模板化成员函数的存在 [英] Use SFINAE to detect the existence of a templated member function
本文介绍了使用SFINAE检测模板化成员函数的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我了解到SFINAE可用于确定类中是否存在成员函数。例如,以下代码可用于检查类中是否存在方法 hello
。
I learned SFINAE can be used to determine whether a member function exists in a class or not. For example, the following code can be used to check if the method hello
is present in a class.
struct has_method_hello {
using yes = char[1];
using no = char[2];
template <typename U, typename C>
static constexpr yes& test(decltype(&U::hello));
template <typename>
static constexpr no& test(...);
static constexpr bool value = (sizeof(yes) == sizeof(test<T>(nullptr)));
};
struct Foo {
void hello() {}
}
std::cout << has_method_hello <Foo> :: value << std::endl; // 1
但是,假设 hello
struct Foo {
template <typename T>
void hello(T&) {...}
}
推荐答案
首先,向您显示原始代码的简化版本:
First of all, showing you a shortened version of your original code:
template <typename T>
struct has_method_hello {
static constexpr auto test(int) -> decltype(std::declval<T&>().hello(), std::true_type());
static constexpr std::false_type test(...);
using result_type = decltype(test(0));
static const bool value = result_type::value;
};
struct Foo {
void hello() {}
};
现在使其适用于模板参数,简单,例如:
Now making it work for a template parameter, easy, an example:
template <typename T>
struct has_method_hello {
static constexpr auto test(int) -> decltype(std::declval<T&>().hello(std::declval<int&>()), std::true_type());
static constexpr std::false_type test(...);
using result_type = decltype(test(0));
static const bool value = result_type::value;
};
struct Foo {
template <typename T>
void hello(T& v) {}
};
请注意,我已经硬编码了 int
类型这里。您也可以将其作为 has_method_hello
模板的一部分。
Note that, I have hardcoded int
type here. You can make that part of has_method_hello
template too.
这篇关于使用SFINAE检测模板化成员函数的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文