dimanche 2 avril 2017

std::function check inheritance of classes

How to enclose std::is_base_of in a std::function practically?

I don't think it is possible, because the type is erased.

How to workaround? I want to cache std::function f. It will be called later.

#include <iostream>
#include <type_traits>
#include <functional>
using namespace std;
class B{ };
class C: B{};
int main(){
    std::cout<<std::is_base_of<B,C>()<<std::endl; //print 1
    std::function<bool()> f=[](X)->bool{  //<--- syntax error (X is class name)
        return std::is_base_of<B,X>();
    };
    std::cout<<f(C)<<std::endl;   //<--- possible? (should print 1)
    return 0;
}

In real case, f is called in a far-away location of code, and I don't want to instantiate B or C.
(Thus, I can't use dynamic_cast to check.)

Aucun commentaire:

Enregistrer un commentaire