-3

I keep getting that weird compile error "LNK2019 unresolved external symbol" c++. I want to create a template function that will take different class as it's parameter. Event and Items are the classes I have created.

template<typename C>
void viewFunction(C customClass, char ch){
   if(ch = 'E'){
       customClass.printName();
       customClass.printPrice();
   }
   else{
       customClass.printName();
       customClass.printSize();
       customClass.printWeight();
   }
}

Now I called that function in main. The error happens when I try to pass in a class as my template type, I think.

int main{

Event myEvent1;
Event myEvent2;

Item myItem1;
Item myItem2;

viewFunction(myEvent1, 'E');

viewFunction(myItem1, 'I');

viewFunctionmyEvent2, 'E');

viewFunction(myItem2, 'I');

return 0;
}
ShaneJA
  • 1
  • 1

1 Answers1

1

Despite the fact that the code you have shown us is not complete nor compilable, I think I understand your error. You seem to be checking with a runtime argument (your char ch) with a runtime if statement for which functions should be compiled in your template (at compile time).

Templates are not reflection or dynamic typing. The only way to have the function calls change depending on the passed-in type would be through function overload.

Function overload for template functions will eventually be done with Concepts, but is done with SFINAE in the current standard.

If only Event and Item use this function though, I'd recommend plain old function overloading with concrete types, like this.

void viewFunction(const Event& customClass)
{
    customClass.printName();
    customClass.printPrice();
}
void viewFunction(const Item& customClass)
{
    customClass.printName();
    customClass.printSize();
    customClass.printWeight();
}
KABoissonneault
  • 2,359
  • 18
  • 17
  • "Template specialization will eventually be done with Concepts" what you're talking about isn't really template specialization, it's candidate set elimination based on type interfaces. Although there's probably a better way of putting it than that. – TartanLlama Jul 03 '15 at 13:50
  • Maybe I got the wrong term... I guess what you do with Concepts is actually simple function overload but with templated functions? – KABoissonneault Jul 03 '15 at 13:52
  • 1
    Concepts (in their current form) are essentially a method to enable/disable template selection based on the validity and types of expressions involving a template parameter. We do that currently using expression SFINAE. – TartanLlama Jul 03 '15 at 13:55
  • Thanks! KABoissonneault – ShaneJA Jul 03 '15 at 13:56
  • @ShaneJA If you copy/paste my code, make sure printName/printPrice/printSize/printWeight are const qualified so they can be called on const variables. Or make the customClass argument not const – KABoissonneault Jul 03 '15 at 13:57