1

Template member functions allow us to parameterise functions independently for a class they belong to. They are supported for both template and non-template classes and it worked fine if we directly call it from class object. But in case if class is composed-off in other class c++ compiler fail to resolve it. In my case I am able to call template member function directly from object but it fails( MsgParser::run(){source.showType();}) when object is composition. logic behind it ?

struct A{};    
struct B{};    
class DataSource{
    public:
        template<class Type>    
        void showType(){
        std::cout<<std::endl<<typeid(Type).name();    
    }
    void disp(){ std::cout<<std::endl<<"All OK";}    
    private:    
};      
    
template<class Source>    
class MsgParser{    
public:    
    MsgParser(Source &s):source(s){}    
    void run(){    
        source.disp();    
        source.showType<A>(); // failed to call ??     
    }       
private:    
    Source &source;    
};      
    
int main()    
{    
    DataSource dataSource;    
    dataSource.showType<A>();
    MsgParser<DataSource> msgParser(dataSource); 
    msgParser.run();    
    return 1;    
} 
Aditya Kumar
  • 155
  • 6

1 Answers1

4

Something like

 source.showType < A > (b);

is ambigious to the compiler not knowing yet what kind of template argument you will pass to it. It might as well be a class member showType inside source that is compared to A and b. Therefore you will have to add .template to the call of showType to distinguish it from a comparison

 source. template showType<A>();

Try it here!

If you are interested in when to add typename and template refer to this lengthy explanation.

2b-t
  • 2,414
  • 1
  • 10
  • 18
  • @AdityaKumar I linked a detailed explanation. It is basically there to distinguish it from a simple comparison. Wait a second, I will add a more detailed explanation. – 2b-t Jul 30 '21 at 07:38
  • 1
    @AdityaKumar I suggest you to understand first why you need to use `typename` for a depedent name, the reason why you need to put `. template` is basically the same – 463035818_is_not_an_ai Jul 30 '21 at 07:39