0

While compiling my code, I keep getting the following linker error (the code compiles fine)

foo.cc:15: undefined reference to `void foo<int, int (*)(int)>(int*, unsigned long, int (*)(int))'

I'm fairly new to C++, and I'm pretty certain that my issue is coming from using template arguments, but I'm not sure where I am going wrong. The header for function foo and how it is being called is shown below

template<typename T, typename F>
void foo(T* a, size_t b, F c);
...
// neither of these work
foo(ptr,val,func);
foo<int, int (*)(int)>(ptr,val,func);

and my implementation of foo is compiling fine. I'm not sure where the issue is coming from.

  • 1
    Where are `ptr`, `val`, and `func` definitions? – wcochran Jan 23 '21 at 21:09
  • ptr is an int*, val is a size_t, and func is `int bar(int a);` – user13106509 Jan 23 '21 at 21:12
  • BTW, even if you get this to work it is far from best practice. C++ provides superior mechanisms for passing functions -- use them. – wcochran Jan 23 '21 at 21:12
  • such as? I initially wanted to use template arguments similar to but that didn't work either – user13106509 Jan 23 '21 at 21:14
  • Template parameters and function parameters are two completely different things in C++. – Sam Varshavchik Jan 23 '21 at 21:14
  • 1
    @wcochran This looks like standard practice to me. Pretty much all standard library function that accept callables use a single template parameter and pass them by value. – super Jan 23 '21 at 21:16
  • @super Best practices would have you pass function objects. You can'y even use the lambda facility in this case. This works but is fragile. – wcochran Jan 23 '21 at 21:19
  • BTW, both cases work when I try it. You might want to give a fuller example. – wcochran Jan 23 '21 at 21:20
  • moving the implementation from a cc to a header file fixed the issue – user13106509 Jan 23 '21 at 21:20
  • 1
    @wcochran Ofc you can pass in a lambda with this code. This is literally the exact same pattern used by the standard library. Not really sure what you're talking about. – super Jan 23 '21 at 21:21
  • @user13106509 -- yes -- the template needs to be somewhere where the compiler can instantiate it. – wcochran Jan 23 '21 at 21:21
  • @super my bad -- you are right -- I guess I was focusing more on the instantiation of the template where a ptr is passed -- that part I wouldn't do. – wcochran Jan 23 '21 at 21:23

0 Answers0