1

I was trying to use some modern c++ dark magic, in order to test if a class has a member function called funcA.

And... it backfired...

It worked perfectly using "g++ -std=c++17 main.cpp".

But when I compiled the same code with "clang++ -std=c++17 main.cpp", it returned false even that the class had this function!

Can you suggest how to over come this problem? Assuming that I must use clang++.

#include <iostream>
#include <type_traits>
template <typename, typename, typename = void>
struct HasFuncA : std::false_type {};
template <typename T, typename S>
struct HasFuncA<T, S, std::void_t<decltype(std::declval<T>().template funcA(std::declval<S>()))>> : std::true_type {};

class MyClass
{
public:
    void funcA(int) const{}
};

int main(){
    std::cout<<HasFuncA<MyClass, int>()<<std::endl;
    return 0;
}   
cigien
  • 57,834
  • 11
  • 73
  • 112
Danny Cohen
  • 505
  • 1
  • 5
  • 11
  • 1
    see https://stackoverflow.com/questions/257288/templated-check-for-the-existence-of-a-class-member-function for how to achieve the goal – M.M Dec 14 '20 at 00:42
  • @M.M thanks for that. I see that this link talks about functions with no parameters. I want to check if the class has funcA function with specific parameter as input. Any idea on how to use the answer in the link for that? – Danny Cohen Dec 14 '20 at 00:50
  • 1
    Why `template funcA`? `funcA` is not a template. Without `template`, your code [produces expected outcome](https://godbolt.org/z/Eoxrj8) – Igor Tandetnik Dec 14 '20 at 01:43
  • Please add the c++ tag to C++ questions so that more users see it. – cigien Dec 14 '20 at 01:48

1 Answers1

0

@Igor Tandetnik answer solved the problem.

I removed the word template from this line

struct HasFuncA<T, S, std::void_t<decltype(std::declval<T>().template funcA(std::declval<S>()))>> : std::true_type {};
==>
struct HasFuncA<T, S, std::void_t<decltype(std::declval<T>(). funcA(std::declval<S>()))>> : std::true_type {};

and it worked!

Still have no idea what exactly happened.. but this is working now!

Thanks Igor!

Danny Cohen
  • 505
  • 1
  • 5
  • 11