template<int t = 0>
class Test
{
public:
inline Test(void);
inline void Crap(void);
private:
int k;
};
template<>
class Test<0>
{
public:
inline Test(void);
inline void Crap(void);
};
template<int t>
inline Test<t>::Test(void) : k(t)
{
}
inline Test<>::Test(void)
{
}
template<int t>
inline void Test<t>::Crap(void)
{
cout << "bleh" << endl;
}
int main(int argc, char *argv[])
{
Test<> t0;
Test<1> t1;
t0.Crap();
t1.Crap();
return 0;
}
Not specialize some member functions?
I want to share some member functions between template specializations of a class, but I can't seem to get it to work.
I intend Crap() to do the same thing between all specializations, and I want to avoid code duplication so I only have to write it once (in the actual thing I'm making I have several member functions that will be the same between specializations, and several that will vary). However, the above fails to link with unresolved external symbol "public: void __thiscall Test<0>::Crap(void)"
I could put the shared functions in a base class, but a) do I still have guarantee that everything is resolved at compile time, and b) it seems ugly to have to use inheritance to implement a generic programming issue.
An easy solution is to put the common function in a common base class. That should avoid code duplication.
#include <iostream>struct CrapBase { inline void Crap(void);};inline void CrapBase::Crap(void) { std::cout << "bleh" << std::endl;}template<int t = 0>class Test : public CrapBase {public: inline Test(void);private: int k;};template<>class Test<0> : public CrapBase {public: inline Test(void);};template<int t>inline Test<t>::Test(void) : k(t) {}inline Test<>::Test(void) {}int main(int argc, char *argv[]) { Test<> t0; Test<1> t1; t0.Crap(); t1.Crap(); return 0;}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement