2

Consider the following, I want to check if the types I pass off to some other function sf has a member function T::mf that is required by sf, I know the return type and the name but there can by any number of overloads.

After some tinkering (well it is fun..) and googling , I can get something like the code below to work, the problem is that I don't know how to express that print can have a variable number of arguments.

#include <type_traits>
#include <utility>


template <typename T,typename = void>
struct has_write : std::false_type {};

template <typename T>
struct has_write<T, decltype(std::declval<T>().write())> : std::true_type {};


template <typename T, typename R = void , typename ...Args>
struct has_print : std::false_type {};

// cant deduce, specialization never used
template <typename T, typename ...Args>
struct has_print<T, decltype(std::declval<T>().print(std::declval<Args>()...))> : std::true_type {};


struct Foo {
    void write();
};

struct Bar {
    int print(int, float, int);
};

int main(){
    static_assert(has_write<Foo>::value, "Does not have write..");
    static_assert(has_print<Bar>::value, "Does not have print..");
    return 0;
}

The above compiles with g++ but the second assert fails, clang is a bit more helpful and tells me that the specializations for has_print will never be used because it cannot deduce all the types.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
arynaq
  • 6,710
  • 9
  • 44
  • 74
  • 1
    AFAIK the only way of doing this is to try to call `print` with 0..N instances of a type that is implicitly convertible to anything. Reflection should make this easier in the future... – Vittorio Romeo Jul 14 '17 at 15:34
  • 1
    Well, since your `sf` function would call a specific version of `print` with a specific number of arguments known to that function, you can check for specific `has_print` with known types. – SergeyA Jul 14 '17 at 15:36
  • I considered that, but I am new to this and for the sake of learning wanted to know a clean way of (pretending this is not a xy problem) finding whether a type has any overloads. – arynaq Jul 14 '17 at 15:38

1 Answers1

2

Since you will be calling your overload from within sf function, you should check for availability of the particular overload using the types sf function would call it with.

General checking for availability of any overload within a class would always be an XY problem by definition, because availability of any overload is never important. You need to know you can call a name with given set of arguments. Consider this: asking for availability of any overload of a given name is conceptually the same as asking if particular class has any method at all. And obviously you would not be interested in it?

SergeyA
  • 61,605
  • 5
  • 78
  • 137