Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to recognize type



  • hi guys
    @template<class T>
    static bool lessOrMoreThan(const T &, const T &,int lessOrMoreFlag)
    {
    if(lessOrMoreFlag == 0){
    ;
    }
    if(lessOrMoreFlag == 1){
    ;
    }
    }@

    if I pass QString or int in this template function, How can I know the exact type I passed in? thanks any comments



  • What do you mean exactly? Can you elaborate?



  • @template<class T>
    static bool lessOrMoreThan(const T &, const T &,int lessOrMoreFlag)
    {
    if(lessOrMoreFlag == 0){
    if(T == QString);
    {
    do something;
    }
    if(T == int)
    {
    do something;
    }else{
    do something
    }
    }
    if(lessOrMoreFlag == 1){
    ;
    }
    }@



  • thank you for your interest, I post a piece of new code above.any comments



  • Do you actually need templates? May be you can try just overloading for types you need



  • [quote author="Kxyu" date="1321640229"]Do you actually need templates? May be you can try just overloading for types you need[/quote]

    that is a good way, but too much.



  • If you need to know the type of the template in a method, this is a strong sign of wrong design and that you most probably shouldn't use a template at all.

    Can you describe what you want to achieve? Maybe we can come up with a better suitable and less problematic idea.



  • you are right. I use other way and fix my problem already.anyway,thanks guys



  • You can specialize your template function to your desired types. This is a standard feature of C++, you can find it under "Specialized Template Functions" or something like that.



  • Yeah, you're right! It's awkward that I've missed that on Stroustrup. So you can just define your template function and then overload it for types that need some special action.


Log in to reply