[英]Specializing a class template constructor
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 ... \\ main.cpp(29):错误C3860:跟随类模板名称的模板参数列表必须按照模板参数列表中使用的顺序列出参数... \\ main.cpp(29):错误C2976:'Die':模板参数太少... \\ main.cpp(31):错误C3860:类模板名称后面的模板参数列表必须按模板参数列表中使用的顺序列出参数
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. 这些就是我在Microsoft Visual Studio 2010中遇到的错误。我在想我不能为专业化找到正确的语法,或者也许无法以这种方式进行。
Your constructor is not a template function. 您的构造函数不是模板函数。 You should specialize the whole class.
您应该对整个班级进行专攻。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.