c++ - 如何检查成员函数是否有 const 重载?

标签 c++ templates c++11

假设我有

struct foo {
    void ham() {}
    void ham() const {}
};

struct bar {
    void ham() {}
};

假设我有一个模板化函数,我能否判断给定类型是否具有 ham 的 const 重载?

最佳答案

#define DEFINE_HAS_SIGNATURE(traitsName, funcName, signature)               \
    template <typename U>                                                   \
    class traitsName                                                        \
    {                                                                       \
    private:                                                                \
        template<typename T, T> struct helper;                              \
        template<typename T>                                                \
        static std::uint8_t check(helper<signature, &funcName>*);           \
        template<typename T> static std::uint16_t check(...);               \
    public:                                                                 \
        static                                                              \
        constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t); \
    }

DEFINE_HAS_SIGNATURE(has_ham_const, T::ham, void (T::*)() const);

然后

static_assert(has_ham_const<foo>::value, "unexpected");
static_assert(!has_ham_const<bar>::value, "unexpected");

Demo

关于c++ - 如何检查成员函数是否有 const 重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35348561/

相关文章:

c++ - std::bind 和右值引用

c++ - 无法在我的 OSX 中编译 "hello world"cpp

即使 C++ 函数不应该运行,它也会运行?

c++ - 如何修复 'Size of list( a class) is unknown or zero error' 和 'Declaration Syntax error' ?

模板的 C++ 错误和推导的参数冲突类型

c++ - 当我应该使用 std::map::at 来检索 map 元素时

c++ - 尝试使用 Oracle Solaris Studio 12.3 在 Solaris 10 上编译 libpqxx-4.0.1 时出错

c++ - 模板类型参数的模板参数必须是一个类型

c++ - 为什么我应该显式地将类型名传递给 std::forward?

c++ - 偏序可变参数模板函数 clang