Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compile time check if method exists in template type

Tags:

c++

templates

I have a template that calls a member function. How do I check with static_assert that the method exists?

struct A {

};

struct B {
    int foo() { return 42; } };

template <typename T> struct D {
    static_assert(/* T has foo */, "T needs foo for reasons");

    int bar() {
       return t.foo();
    }

    T t; };

int main() {
    D<A> d;

    std::cout << d.bar() << std::endl;

    return 0; }

I know this will just generate a compiler error that A does not have foo but I would like to check and give a better error output using static_assert.

like image 206
Mochan Avatar asked Mar 15 '19 22:03

Mochan


2 Answers

Since you use static_assert I assert that you are using at least C++11. This allows to write something like this:

#include <type_traits>

template<class ...Ts>
struct voider{
    using type = void;
};

template<class T, class = void>
struct has_foo : std::false_type{};

template<class T>
struct has_foo<T, typename voider<decltype(std::declval<T>().foo())>::type> : std::true_type{};

And you just use static field value (has_foo<your_type>::value) - if it's true then your type has function foo.

like image 170
bartop Avatar answered Nov 11 '22 02:11

bartop


Constraint templates has been a long discussion - ever since 2005 or so - on std forums. But the outcome has yet to wait til C++20.

like image 45
Red.Wave Avatar answered Nov 11 '22 02:11

Red.Wave