使用 C++17 检测类成员是否存在

ale*_*ibs 1 c++ c++17

7 年前,我会这样写:

#include <iostream>

struct A {};

struct B {
    static const char* message;
};
const char* B::message = "Hello, world!";

template <typename T>
void PrintMessage(...) {}

template <typename T>
void PrintMessage(decltype(&T::message)) {
    std::cout << T::message << std::endl;
}

int main() {
    PrintMessage<A>(nullptr);
    PrintMessage<B>(nullptr);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

https://ideone.com/sVP6AY

如果我没记错的话,该解决方案甚至可以与 Visual C++ 2010 一起使用。在 C++ 17 中有没有更好的方法来做到这一点?

Mes*_*kon 7

如果您知道要检查哪个函数或成员,您可以创建一个 type_trait

template<class T, class = void>
struct has_message : std::false_type { };

template<class T>
struct has_message<T, std::void_t<decltype(T::message)>> : std::true_type { };

template<class T>
void PrintMessage()
{
    if constexpr (has_message<T>::value)
        std::cout << T::message << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 您应该观看 CppCon 2014 上的 [Walter Brown's](https://www.youtube.com/watch?v=a0FliKwcwXE) 演示 - 大约 29:00 开始 (2认同)