Проверьте, есть ли в классе возможно перегруженный оператор вызова функции

Мне интересно, можно ли реализовать трейт в C++20, чтобы проверить, является ли тип T таким, что он имеет, возможно, перегруженный/возможно шаблонный оператор вызова функции: operator().

// Declaration
template <class T>
struct has_function_call_operator;

// Definition
???  

// Variable template
template <class T>
inline constexpr bool has_function_call_operator_v 
= has_function_call_operator<T>::value;

так что код, подобный следующему, приведет к правильному результату:

#include <iostream>
#include <type_traits>

struct no_function_call_operator {
};

struct one_function_call_operator {
    constexpr void operator()(int) noexcept;
};

struct overloaded_function_call_operator {
    constexpr void operator()(int) noexcept;
    constexpr void operator()(double) noexcept;
    constexpr void operator()(int, double) noexcept;
};

struct templated_function_call_operator {
    template <class... Args>
    constexpr void operator()(Args&&...) noexcept;
};

struct mixed_function_call_operator
: overloaded_function_call_operator
, templated_function_call_operator {
};

template <class T>
struct has_function_call_operator: std::false_type {};

template <class T>
requires std::is_member_function_pointer_v<decltype(&T::operator())>
struct has_function_call_operator<T>: std::true_type {};

template <class T>
inline constexpr bool has_function_call_operator_v 
= has_function_call_operator<T>::value;

int main(int argc, char* argv[]) {
    std::cout << has_function_call_operator_v<no_function_call_operator>;
    std::cout << has_function_call_operator_v<one_function_call_operator>;
    std::cout << has_function_call_operator_v<overloaded_function_call_operator>;
    std::cout << has_function_call_operator_v<templated_function_call_operator>;
    std::cout << has_function_call_operator_v<mixed_function_call_operator>;
    std::cout << std::endl;
}

В настоящее время он печатает 01000 вместо 01111. Если это невыполнимо в самом широком смысле, можно предположить, что T наследуется, если это поможет. Приветствуются самые странные приемы метапрограммирования шаблонов, если они полностью соответствуют стандарту C++20.


person Vincent    schedule 15.06.2020    source источник
comment
&T::operator() неоднозначно для 3 неудачных случаев.   -  person Jarod42    schedule 16.06.2020
comment
Почему ты вообще хочешь это знать? Что хорошего в знании того, что функция существует, если вы не знаете, как ее вызвать?   -  person Nicol Bolas    schedule 16.06.2020
comment
Я чувствую, что это действительный дубликат.   -  person Nicol Bolas    schedule 16.06.2020


Ответы (1)


&T::operator() неоднозначно для 3 неудачных случаев.

Итак, ваши черты найдены, есть однозначное operator()

Поскольку вы разрешаете T быть не final, мы можем применить ваши признаки к (фальшивому) классу с существующим унаследованным operator() и классом для тестирования:

template <class T>
struct has_one_function_call_operator: std::false_type {};

template <class T>
requires std::is_member_function_pointer_v<decltype(&T::operator())>
struct has_one_function_call_operator<T>: std::true_type {};

struct WithOp
{
    void operator()() const;  
};

template <typename T>
struct Mixin : T, WithOp {};

// if T has no `operator()`, Mixin<T> has unambiguous `operator()` coming from `WithOp`
// else Mixin<T> has ambiguous `operator()`
template <class T>
using has_function_call_operator =
    std::bool_constant<!has_one_function_call_operator<Mixin<T>>::value>;

template <class T>
inline constexpr bool has_function_call_operator_v 
= has_function_call_operator<T>::value;

Демо

person Jarod42    schedule 16.06.2020