C 检测是否存在接受特定类型的函数

C++ Detect if there exists a function by name that accepts a particular type

本文关键字:类型 函数 检测 是否 存在      更新时间:2023-10-16

我想检测到给定类型的插入操作员。通常,我会检查具有适当签名的超载函数。说我有A类,然后

template<typename T>
struct insert_operator_type
{
   using type = typename std::ostream&(*)(std::ostream&, const T&);
};
...
std::is_same<
        decltype(static_cast<typename insert_operator_type<A>::type> (&operator<<)),
        std::ostream&(*)(std::ostream&, A const&)
     >::value 

会告诉我他们是一样的,我可以推断出操作员存在。与运营商Lt;&lt;但是,A型B类型可能会分解为A型。说

之类的话
template<typename T>
class A 
{
public:
    T* type1 = nullptr;
};
typedef A<int>  BImpl;
class B : public BImpl
{
public:
    B() {}
};
template<typename T>
std::ostream& operator<<(std::ostream& os, const A<T>& a)
{
    os << "printing A<T>" << std::endl;
    return os;
}

现在我可以

 B b;
 std::cout << b << std::endl;

但是没有

std::ostream&(*)(std::ostream&, B const&)

相反

我可以确定存在过载的函数,以便无法为特定类型指定该函数,而是针对给定类型的某种类型会转换为?

您可能只想使用sfinae检查整个表达式插入是否有效。

// std::void_t in C++1z
template <class...>
using void_t = void;
template <class, class = void_t<>>
struct can_be_ostreamed : std::false_type { };
template <class T>
struct can_be_ostreamed<T, void_t<
    decltype(std::declval<std::ostream&>() << std::declval<T>())
>> : std::true_type { };

生活在coliru