user1832484
user1832484

Reputation: 371

Detect if a function/operator/method having certain signature is defined

Coming from this question, how can we detect (at compile time) if a function/operator/method having certain signature is defined?

From linked question and looking at cppreference about std::void_t we can write (C++17 ahead)

#include<iostream>
#include<type_traits>
#include<utility>

class X { public: int someFunc() const{ return 9; } };
class Y{};

template<typename, typename = std::void_t<>> struct Has_someFunc
    : std::false_type{};
template<typename T> struct Has_someFunc<T, std::void_t<decltype(std::declval<T>().someFunc())>>
    : std::true_type{};

template<typename T>
void f(const T& v){
    if constexpr(Has_someFunc<T>::value)
        std::cout << "has someFunc()\n";
    else
        std::cout << "has NOT someFunc()\n";
}

int main()
{
    std::cout << "X "; f(X{});
    std::cout << "Y "; f(Y{});

    return 0;
}

which prints

X has someFunc()
Y has NOT someFunc()

but what if we want to test a type to have someFunc not only to be defined but also having a certain signature?

Though I'm using C++17 also answers in any other version of the standard are welcome.

Upvotes: 0

Views: 160

Answers (1)

max66
max66

Reputation: 66200

If you intend check if a type has a method someFunc() that is compatible (in-vocable with) a given signature) and return a given type, you can modify your code as follows

#include<iostream>
#include<type_traits>
#include<utility>

class X
 { public: int someFunc (int, long) const { return 9; } };

class Y
 { };

template <typename, typename = void>
struct Has_someFunc : public std::false_type
 { };

template <typename T, typename RType, typename ... Args>
struct Has_someFunc<std::tuple<T, RType, Args...>, std::enable_if_t<
   std::is_same_v<RType, 
      decltype(std::declval<T>().someFunc(std::declval<Args>()...))>>>
    : public std::true_type
 { };

template <typename RType, typename ... Args, typename T>
void f (T const & v)
 {
   if constexpr (Has_someFunc<std::tuple<T, RType, Args...>>::value)
      std::cout << "has someFunc()\n";
   else
      std::cout << "has NOT someFunc()\n";
 }

int main()
{
    std::cout << "X "; f<int>(X{});
    std::cout << "X "; f<int, int, long>(X{});
    std::cout << "X "; f<int, int, int>(X{});
    std::cout << "Y "; f<int>(Y{});
}

Drawback: you get "has someFunc()" also from third invocation because the last argument (a int) is compatible with the last expected argument (a long).

Upvotes: 1

Related Questions