检查类是否有函数(返回类型和const检查)

时间:2015-09-15 17:25:55

标签: c++ templates c++11 template-meta-programming

鉴于

class A {
public:
    bool foo(int) const {return true;}
};

我想要HasFooWithStringReturnTypeAndIsConst<A>::valueHasFooWithBoolReturnTypeAndIsNotConst<A>::value为false(HasFooWithBoolReturnTypeAndIsConst<A>::value已经返回true,因此工作正常)。这就是我所拥有的:

#include <iostream>
#include <type_traits>
#include <string>

class A {
public:
    bool foo(int) const {return true;}
};

template <typename...> struct voider {using type = void;};

template <typename... Ts>
using void_t = typename voider<Ts...>::type;

template <typename T, typename = void_t<T>>
struct HasFooWithBoolReturnTypeAndIsNotConst : std::false_type {};

template <typename T>
struct HasFooWithBoolReturnTypeAndIsNotConst<T,
        void_t<decltype(std::declval<T&>().foo(std::declval<int>()))>> {
    using Foo = bool (T::*)(int);
    template <typename U> static std::true_type test (Foo*);
    template <typename U> static std::false_type test (...);
    static constexpr bool value = std::is_same<decltype(test<T>(nullptr)), std::true_type>::value;
};

template <typename T, typename = void_t<T>>
struct HasFooWithStringReturnTypeAndIsConst : std::false_type {};

template <typename T>
struct HasFooWithStringReturnTypeAndIsConst<T,
        void_t<decltype(std::declval<T&>().foo(std::declval<int>()))>> {
    using Foo = std::string (T::*)(int) const;
    template <typename U> static std::true_type test (Foo*);
    template <typename U> static std::false_type test (...);
    static constexpr bool value = std::is_same<decltype(test<T>(nullptr)), std::true_type>::value;
};

int main() {
    std::cout << HasFooWithStringReturnTypeAndIsConst<A>::value << '\n';  // true (should be false!)
    std::cout << HasFooWithBoolReturnTypeAndIsNotConst<A>::value << '\n';  // true (should be false!)
}

有人可以解释为什么他们会返回true而不是false吗?如何修复它们以使它们返回false? A::foo(int)是一个返回bool的const函数,所以它们应该返回false,不是吗?

1 个答案:

答案 0 :(得分:2)

您的支票适用于:

decltype(test<T>(nullptr))

两个重载是:

template <typename U> static std::true_type test(Foo*);
template <typename U> static std::false_type test(...);

这里没有你真正考虑&T::foo。您只是检查是否可以将nullptr转换为某种任意指针类型。当然,你可以。这就是它最终成为true_type的原因。您要检查的是,您是否可以将&T::foo专门转换为该类型:

template <typename U> static std::true_type test (std::string (U::*)(int) const );
template <typename U> static std::false_type test (...);
static constexpr bool value = decltype(test<T>(&T::foo))::value;

请注意,您可以直接通过以下方式在部分特化中更简单地执行此操作:

template <typename T>
struct HasFooWithStringReturnTypeAndIsConst<T,
            std::enable_if_t<
                std::is_same<std::string,
                             decltype(std::declval<const T&>().foo(0))
                             >::value
            >> : std::true_type { };

在此处,我们通过在foo()上调用const来检查const T&是否std::string,然后只需检查其返回类型是否为{{1}}。

相关问题