0

I want to write a templatized function in C++ where 4 total items are templatized (T, T2, T3, T4). Two of these appear as parameters in the function (T3 and T4). However, there are two other items that I want to templatize (T and T2) that are present only in the function body, not in the parameter list.

template <typename T, typename T2, typename T3, typename T4>
void foo (T3 edges, T4 distance)
{
 ...
 T xmin;
 T2 normal;
 ...
}

When I try to do this, I get compiler errors for "undefined reference to foo". Any recommendations for how to templatize items that are only present in the function body, not the parameter list?

Note: foo is defined in a cpp file, and then I have specific instantiations also in the cpp file.

nordstar
  • 1
  • 1
  • Where is `foo` defined? [This](https://stackoverflow.com/q/495021/3309790) might help. – songyuanyao Dec 16 '21 at 01:18
  • 1
    As a design note, it seems like the types `T` and `T2` ought to be related to `T3` and `T4`. Have you considered making them dependent types? E.g. Replace `T` with something like `T3::weight_type` or `edge_traits::weight_type` and define the required type alias/trait specialization for your edge class? – Brian61354270 Dec 16 '21 at 01:21
  • 90% chance this is your issue: https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – NathanOliver Dec 16 '21 at 02:53
  • @songyuanyao, I added where foo is defined. – nordstar Dec 16 '21 at 17:04
  • Please provide enough code so others can better understand or reproduce the problem. – Community Dec 22 '21 at 19:02

1 Answers1

0

You need to implement your function template foo<> inside a header as shown in the example below:

mytemplates.h

#ifndef MYTEMPLATE_H
#define MYTEMPLATE_H
template <typename T, typename T2, typename T3, typename T4>
void foo (T3 edges, T4 distance)
{
 
 T xmin;
 T2 normal;
 
 
}
#endif

main.cpp

#include <iostream>
#include <string>
#include "mytemplates.h"


int main() 
{
    std::string s = "name";
    foo<int, float>("string literal", s);
  
}

The output of the program can be seen here.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • Thanks Anoop, but since I have the definition & specific instantiations in the cpp file, I don't think that this is my issue. – nordstar Dec 16 '21 at 17:03
  • @nordstar You're welcome. Can you provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) so that we don't have to guess what files you have and what you're actually doing. We don't have anything to correct/modify in your current program. – Jason Dec 16 '21 at 17:15