I
Improving
I have a template class that has static members, so in the .cpp file I
have defined them with templated definitions. Now when in a different
..cpp file that includes the header file for the template class I derive
a new class from the template class and pass that class as its template
parameter (CRTP). Now when I instantiate this new class it complains it
cannot find the statics. Doesnt the template definition define them?
The code compiles fine but causes linker errors.
heres a boiled down example of whats causing the trouble....
header....
#ifndef CTYPE
#define CTYPE
#include <cstddef>
namespace ns
{
template <typename CT>
class OC
{
public:
static std::size_t count()
{
return OC<CT>::c_;
}
protected:
OC()
{
++OC<CT >::c_;
}
OC( const OC< CT >& )
{
++OC< CT >::c_;
}
~OC()
{
--OC< CT >::c_;
}
private:
static std::size_t c_;
};
}
#endif
..cpp ....
#include "templates.h"
namespace ns
{
// mandatory static definition
template < typename CT >
std::size_t OC< CT >::c_ = 0;
}
main.cpp
#include "templates.h"
#include <iostream>
using namespace std;
class C : private ns::OC<C>
{
public:
using ns::OC<C>::count;
};
int main()
{
C array[3];
cout << C::count()<<endl;
return 0;
}
How do I make my code linkable as well as compileable?
have defined them with templated definitions. Now when in a different
..cpp file that includes the header file for the template class I derive
a new class from the template class and pass that class as its template
parameter (CRTP). Now when I instantiate this new class it complains it
cannot find the statics. Doesnt the template definition define them?
The code compiles fine but causes linker errors.
heres a boiled down example of whats causing the trouble....
header....
#ifndef CTYPE
#define CTYPE
#include <cstddef>
namespace ns
{
template <typename CT>
class OC
{
public:
static std::size_t count()
{
return OC<CT>::c_;
}
protected:
OC()
{
++OC<CT >::c_;
}
OC( const OC< CT >& )
{
++OC< CT >::c_;
}
~OC()
{
--OC< CT >::c_;
}
private:
static std::size_t c_;
};
}
#endif
..cpp ....
#include "templates.h"
namespace ns
{
// mandatory static definition
template < typename CT >
std::size_t OC< CT >::c_ = 0;
}
main.cpp
#include "templates.h"
#include <iostream>
using namespace std;
class C : private ns::OC<C>
{
public:
using ns::OC<C>::count;
};
int main()
{
C array[3];
cout << C::count()<<endl;
return 0;
}
How do I make my code linkable as well as compileable?