我想知道是否可以实现一个特征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
标准,最奇怪的模板元编程技巧都是受欢迎的。