提问者:小点点

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


共1个答案

匿名用户

如果您知道要检查哪个函数或成员,则可以创建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;
}

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++17|检测|类|成员)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?