alexeibs
alexeibs

Reputation: 545

Detecting if a class member exists with C++17

7 years ago I would write something like that:

#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

The solution would work even with Visual C++ 2010 if I recall correctly. Is there any better way of doing that in C++ 17 ?

Upvotes: 4

Views: 1158

Answers (1)

Mestkon
Mestkon

Reputation: 4046

If you know which function or member you would like to check you can create a 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;
}

Upvotes: 11

Related Questions