检查是否存在(重载)成员函数 [英] Checking for existence of an (overloaded) member function
问题描述
There are a number of answered questions about checking whether a member function exists: for example, Is it possible to write a template to check for a function's existence?
但是,如果函数重载,则此方法失败。这是该问题的最高评分答案中经过稍微修改的代码。
But this method fails, if the function is overloaded. Here is a slightly modified code from that question's top-rated answer.
#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
如果第二个 helloworld()
被注释掉了。
if the second helloworld()
is commented out.
所以我的问题
推荐答案
在C ++中,不可能[到目前为止] ]以获取重载集的地址:当您获取函数或成员函数的地址时,该函数要么是唯一的,要么需要选择适当的指针,例如,通过将指针立即传递给合适的函数或通过铸造。换句话说,如果 helloworld
不是唯一的,则表达式& C :: helloworld
将失败。据我所知,结果是无法确定是否可能存在重载的名称作为类成员或正常函数存在。
In C++ it impossible [so far] to take the address of an overload set: when you take the address of a function or a member function the function is either unique or it is necessary to have the appropriate pointer be chosen, e.g., by passing the pointer immediately to a suitable function or by casting it. Put differently, the expression &C::helloworld
fails if helloworld
isn't unique. As far as I know the result is that it is not possible to determine whether a possibly overloaded name is present as a class member or as a normal function.
通常,但是,我需要用名称做些事情。也就是说,如果足以知道某个函数是否存在,并且可以使用一组指定类型的参数来调用,则该问题将大为不同:可以通过尝试相应的操作来回答该问题。调用并在可支持SFINAE的上下文中确定其类型,例如:
Typically you'll need to do something with the name, however. That is, if it is sufficient to know if a function is present and can be called with a set of arguments of specified type, the question becomes a lot different: this question can be answered by attempting a corresponding call and determining its type in a SFINAE-able context, e.g.:
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
这篇关于检查是否存在(重载)成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!