检测是否存在具有 C++17 的类成员
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 中是否有更好的方法?
如果您知道要检查哪个函数或成员,则可以创建一个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;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 数据成员SFINAE的C++17测试:gcc vs clang
- 检测是否存在具有 C++17 的类成员
- 如何在C++17中使用type_traits检测具有特定名称和签名的函数(NOT类成员)的存在
- C++17静态内联成员的编译器错误
- 为什么C 17中的全局内线变量和静态内线成员需要警卫
- 成员函数作为模板参数,C 17等效
- 成员变量在 C++17 中标记为'static' static_assert?
- C 17标准是否保证工会的地址与其成员的地址相同
- 使用 <filesystem> C++17 中的成员的链接错误
- 根据模板参数条件 C++17 创建成员别名
- 在C 17中,为什么关联容器具有``擦除''成员函数,该函数会采用(non-`const`)``iTerator'
- JNI jni/cyberlevel9.c:17:31:错误:请求成员'NewDirectByteBuffer'不是结构或工会