繁体   English   中英

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

[英]Detecting if a class member exists with 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;
}

https://ideone.com/sVP6AY

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

如果您知道要检查的 function 或成员,您可以创建一个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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM