c++ - 方法存在检查器代码在 vs2015 中中断

标签 c++ c++11 visual-studio-2015 msvc12 msvc14

以下代码检查类 A 中是否存在 foo() 方法。此代码在 vs2013 下编译,但在 vs2015 上静态断言失败。哪个编译器版本说的是实话?如果是vs2015,那么如何修复代码?

#include <type_traits>

struct MethodTester_foo {
    template<typename U, typename MethodType>
    static auto test(U* p) -> decltype(static_cast<MethodType>(U::foo));
    template<typename U, typename MethodType> static auto test(...)->std::false_type;
};

template <typename Class, typename MethodType, class MethodTester>
using HasMethod =
typename std::conditional
<
    std::is_same<
        decltype(MethodTester::template test<Class, MethodType>(0)),
        std::false_type
    >::value,
    std::false_type, std::true_type
>::type;

struct A { int foo() { return 1; } };

static_assert(HasMethod<A, int(A::*)(), MethodTester_foo>::value, "Has no method named foo");

最佳答案

2015 年是正确的。您需要 &U::foo 而不是 U::foo&ClassName::methodName 是在 C++ 中获取成员函数指针的唯一方法。


顺便说一句,您的代码可以大大简化:

#include <type_traits>

struct MethodTester_foo {
    template<typename U, typename MethodType, typename = decltype(static_cast<MethodType>(&U::foo))>
    static auto test(U* p) -> std::true_type;
    template<typename U, typename MethodType>
    static auto test(...) -> std::false_type;
};

template <typename Class, typename MethodType, class MethodTester>
using HasMethod = decltype(MethodTester::template test<Class, MethodType>(0));

struct A { int foo() { return 1; } };

static_assert(HasMethod<A, int(A::*)(), MethodTester_foo>::value, "Has no method named foo");

关于c++ - 方法存在检查器代码在 vs2015 中中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42030684/

相关文章:

android - well_known_types_embed.cc -/bin/sh : js_embed: command not found

c++ - LLVM 3.4 与 VS 2012 集成

c++ - append 到 STL 集合

c++ - 具有最少复制的正向仿函数

nuget - 无法将 Nuget 包添加到 ASP.NET vNext 项目

powershell - 包管理器控制台不会初始化

c++ - MYSQL Too many connections 错误不会消失

c++ - 比较两个 vector<Structs> 的字符串元素

c++ - 将来调用 system_clock::now() 可以给出过去的时间吗?

c# - '控制台'不包含 asp.net 5 控制台应用程序中 'ReadKey' 的定义