本文介绍了检查是否存在(重载)成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
但是,如果函数重载,则此方法失败。这是该问题的最高评分答案中经过稍微修改的代码。
#include <iostream>
#include <vector>
struct Hello
{
int helloworld(int x) { return 0; }
int helloworld(std::vector<int> x) { return 0; }
};
struct Generic {};
// SFINAE test
template <typename T>
class has_helloworld
{
typedef char one;
typedef long two;
template <typename C> static one test( decltype(&C::helloworld) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
int
main(int argc, char *argv[])
{
std::cout << has_helloworld<Hello>::value << std::endl;
std::cout << has_helloworld<Generic>::value << std::endl;
return 0;
}
0
0
1
0
if the second helloworld()
is commented out.
推荐答案
template <typename T, typename... Args>
class has_helloworld
{
template <typename C,
typename = decltype( std::declval<C>().helloworld(std::declval<Args>()...) )>
static std::true_type test(int);
template <typename C>
static std::false_type test(...);
public:
static constexpr bool value = decltype(test<T>(0))::value;
};
然后您将使用此类型来确定是否存在可以适当地调用的成员,例如:
You'd then use this type to determine if there is a member which can suitably be called, e.g.:
std::cout << std::boolalpha
<< has_helloworld<Hello>::value << '\n' // false
<< has_helloworld<Hello, int>::value << '\n' // true
<< has_helloworld<Generic>::value << '\n'; // false
这篇关于检查是否存在(重载)成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!