0

I'd like to create a function that takes a template vector object as an argument, which is defined by two template parameters: a type and a dimension.

For example, Vec<float, 3> is a 3D float vector, Vec<int, 2> is a 2D int vector, etc.

I want to create a function that can take a float-type Vec of arbitrary dimension.

I began with this function signature which compiles:

template<int D> void myFunc(Vec<float, D> v);

I'd like to call it like this, which doesn't compile:

// for 2D
myFunc<2>(Vec<float, 2>(x, y));
// for 3D
myFunc<3>(Vec<float, 3>(x, y, z));

and so on.

Is this possible with C++? I suppose overloading the function is a possibility, but I'd like to know if this is possible/practical anyway.

Other details: in my real implementation, this function is a part of a class which is not a template class. I don't need to resolve which dimension I am passing in since the class already knows about the expected dimension from an internal parameter.

Here is the error produced:

Undefined symbols for architecture x86_64:
"int MyClass::myFunc<2>(Vec<float, 2>)", referenced from:
    _main in test-1e56b5.o
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    make: *** [all] Error 1

Thanks.

Sefu
  • 2,404
  • 8
  • 42
  • 59
  • Undefined symbols for architecture x86_64: "void MyClass::myFunc<2>(Vec)", referenced from: _main in test-1e56b5.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [all] Error 1 – Sefu Apr 03 '15 at 20:58
  • Please post an [MCVE](http://stackoverflow.com/help/mcve). – R Sahu Apr 03 '15 at 21:03
  • 1
    My crystal ball tells me this question, ["Why can templates only be implemented in the header file?"](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file?s=1|3.8264) is directly involved with that llinker error. – WhozCraig Apr 03 '15 at 21:05
  • @WhozCraig You are right, that was the issue... wow, thanks! – Sefu Apr 03 '15 at 21:14

1 Answers1

0

As mentioned int he comments, Why can templates only be implemented in the header file? answers the question (I was implementing it in a .cpp file instead of a header). Moving the implementation over the the header fixed the compiler error.

Sefu
  • 2,404
  • 8
  • 42
  • 59