mercredi 1 février 2017

C++ SFINAE activate method only is other class has method

I am trying to use SFINAE to activate a method only if another class has a method related. But after hours of searching I still cannot understand why I get this error "call of overloaded 'run(int)' is ambiguous".

http://ift.tt/2krt6dD

I created this code after looking at :

http://ift.tt/1AiBl8p

Is it possible to write a template to check for a function's existence?

Thank you

#include <iostream>

struct A {
    void printA(int a) {
        printf("A::printA(%d)\n", a);
    }
};

struct B {
    void printB(double b) {
        printf("B::printB(%lf)\n", b);
    }
};

struct Runner {
    A a;
    B b;

    template <class T>
    auto run(const T &x) -> decltype(std::declval<A>().printA(x), void()) {
        a.printA(x);
    }

    template <class T>
    auto run(const T &x) -> decltype(std::declval<B>().printB(x), void()) {
        b.printB(x);
    }
};

int main() {
    Runner runner;
    runner.run(1);
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire