Specializing a class template constructor
- by SilverSun
I'm messing around with template specialization and I ran into a problem with trying to specialize the constructor based on what policy is used. Here is the code I am trying to get to work.
#include <cstdlib>
#include <ctime>
class DiePolicies {
public:
class RollOnConstruction { };
class CallMethod { };
};
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
template<unsigned sides = 6, typename RollPolicy = DiePolicies::RollOnConstruction>
class Die {
// policy type check
BOOST_STATIC_ASSERT(( boost::is_same<RollPolicy, DiePolicies::RollOnConstruction>::value ||
boost::is_same<RollPolicy, DiePolicies::CallMethod>::value ));
unsigned m_die;
unsigned random() { return rand() % sides; }
public:
Die();
void roll() { m_die = random(); }
operator unsigned () { return m_die + 1; }
};
template<unsigned sides>
Die<sides, DiePolicies::RollOnConstruction>::Die() : m_die(random()) { }
template<unsigned sides>
Die<sides, DiePolicies::CallMethod>::Die() : m_die(0) { }
...\main.cpp(29): error C3860: template argument list following class template name must list parameters in the order used in template parameter list
...\main.cpp(29): error C2976: 'Die' : too few template arguments
...\main.cpp(31): error C3860: template argument list following class template name must list parameters in the order used in template parameter list
Those are the errors I get in Microsoft Visual Studio 2010. I'm thinking either I can't figure out the right syntax for the specialization, or maybe it isn't possible to do it this way.