小编ale*_*ibs的帖子

使用 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 中有没有更好的方法来做到这一点?

c++ c++17

1
推荐指数
1
解决办法
93
查看次数

标签 统计

c++ ×1

c++17 ×1