Template type check C++

前端 未结 6 748
日久生厌
日久生厌 2021-01-14 17:48

I have a template function which takes in objects. I need to determine whether the object is derived from a particular base class. If it is derived from the base class, I ne

6条回答
  •  不思量自难忘°
    2021-01-14 18:35

    Without knowing the exact nature of the additional work you want to do, there could be 2 ways might approach this.

    Option 1: Say the function you want to call is foo(). You could implement foo() on both baseA and testB. baseA::foo() can give you your extra work while testB:foo() would just do nothing. But this style wouldn't make sense if foo() doesn't belong in either of those 2 classes.

    Optional 2: Specialize functionA for baseA (or optionally testB as well)

    void function_specialized(baseA* param)
    {
        // Do your extra work
    
        // Then call the common functionA
        functionA(*param);
    }
    
    template
    functionA(const T& value)
    {
       //...
    }
    

提交回复
热议问题