Is it possible to check for existence of member templates just by an identifier?

后端 未结 4 978
醉酒成梦
醉酒成梦 2021-01-04 11:54

Can we detect member function template, variable template, class/struct/union template or alias templ

4条回答
  •  粉色の甜心
    2021-01-04 12:07

    This approach works in the presence of multiple overloads, returning false_type if and only if there are no methods, or members, called bar. It doesn't tell us anything useful about what the bar(s) is/are though (more on that later).

    (Note: This answer (and question?) are dupes. I learned about this technique on SO only a few days ago. But I can't find the original!)

    This uses void_t, which you may need to define yourself (not in c++11, for example):

    template
    struct voider { using type = void; };
    template
    using void_t = typename voider :: type;
    

    bar is the member we are interested in, so we make a really boring struct with a member called bar:

    struct just_a_bar { int bar; };
    

    Then a template, given T, which declares a struct that inherits from both T and just_a_bar.

    template
    struct MultipleBars : public T , public just_a_bar { };
    

    Now, decltype(MultipleBars::bar) will give an ambiguity error if, and only if, there is a member bar in T. We can use this:

    template
    struct has_at_least_one_bar : public true_type {};
    
    template
    struct has_at_least_one_bar::bar) >>
        : public false_type { 
    };
    

    Then, to use the above for real:

    struct zero { };
    struct one { 
        void bar(int,int);
    };
    struct two { 
        //template // works fine with templates too
        void bar(int);
        void bar(int,int);
    };
    
    
    int main() { 
        cout << boolalpha;
        cout << has_at_least_one_bar{} << endl; // false
        cout << has_at_least_one_bar{} << endl;  // true
        cout << has_at_least_one_bar{} << endl;  // true
    }
    

    Once you know bar exists, you probably want more detail. If you have a few specific patterns in mind (non-template member, template method with type parameters only, template method with two int non-type parameters, template method with three template-template parameters, ...) then I think you can test for each of those patterns individually. But ultimately there are limits to what you can detect with a finite number of such patterns. (And the fact that you mean templated methods, not templated structs, might make this more difficult

提交回复
热议问题