This is a follow up question to Storing C++ template function definitions in a .CPP file.
I have a similar problem, using a template class across multiple files, each using the class. In the end they meet in main.cpp and therefore cause a linker error.
The difference to the post above is, that my template doesn't use a type, but a number as its template argument. And putting an instantiation of every possible number in the .cpp file doesn't seem to be a praticable solution ...
someTemplate.hpp
#pragma once
#include <array>
template<const size_t S>
class Foo
{
public:
Foo();
Foo( const std::array<int, S>& someArr );
int& get( const int index );
private:
std::array<int, S> arr;
};
template<size_t S>
inline Foo<S>::Foo()
{
}
template<size_t S>
inline Foo<S>::Foo( const std::array<int, S>& someArr ) : arr( someArr )
{
}
template<size_t S>
inline int& Foo<S>::get( const int index )
{
return arr.at( index );
}
otherFile.hpp
#pragma once
#include "someTemplate.hpp"
class Bar
{
public:
Bar();
Foo<3> doSome( Foo<3>& foo, int m );
};
otherFile.cpp
#include "otherFile.hpp"
Bar::Bar()
{
}
Foo<3> Bar::doSome( Foo<3>& foo, int m )
{
Foo<3> foo;
foo.get( 0 ) = m * foo.get( 0 );
foo.get( 1 ) = m * foo.get( 1 );
foo.get( 2 ) = m * foo.get( 2 );
return foo;
}
main.cpp
#include "otherFile.hpp"
#include "someTemplate.hpp"
int main()
{
Foo<3> foo1( { 1, 2, 3 } );
Bar bar;
Foo<3> foo2 = bar.doSome( foo1, 2 );
return 0;
}
Output
1>------ Build started: Project: testing, Configuration: Debug x64 ------
1>Main.cpp
1>otherFile.cpp
1>D:\Home\Documents\Programming\C++\Visual Studio 2019\testing\otherFile.cpp(10,12): error C2082: redefinition of formal parameter 'foo'
1>Generating Code...
1>Done building project "testing.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
So I can't split the class into definition and declaration, because the compiler won't find it? I can't put it into a single .hpp, because the definition gets included multiple times? But I have to include it into multiple files, because every translation unit needs it. So the question is ...
How can one include a template class into multiple files?
[ PS: The actual code is much bigger, containing templated functions and specializations. I just constructed this simple version for the post. ]
using MSVC ++17 x64
Thanks in advance