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;
}
This code prints out:
0
0
But:
1
0
if the second helloworld()
is commented out.
So my question is whether it's possible to check whether a member function exists, regardless of whether it's overloaded.
0 0
with Clang 3.5.1, but it doesn't compile with GCC 4.9.2. – Millennialtypeof
todecltype
makes both GCC and Clang happy with the above code (but they still produce0 0
). I've updated the code sample to usedecltype
. – Millennialfor (auto&& var : RANGE);
. We can test validity of the expressiondeclval<RangeT &>().begin()
, but not the validity of a statement or the existence of any member namedbegin
, and the Standard says the loop's behavior depends on existence of any membersbegin
andend
. So given a strange type with invalid memberbegin
but valid ADL non-memberbegin
, the trait could call it valid when it's actually invalid. – Isothere