专门构建类模板构造函数 [英] 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) { }
$ b b
... \main.cpp(29):错误C3860:模板参数列表下面的类模板名称必须按照模板参数列表中使用的顺序列出参数
... \main.cpp 29):error C2976:'Die':模板参数太少
... \main.cpp(31):error C3860:模板参数列表下面的类模板名称必须按照模板参数中使用的顺序列出参数列表
...\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
这是我在Microsoft Visual Studio 2010中获得的错误。我想我无法找出正确的语法的专业化,或者也许它是
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.
推荐答案
您的构造函数不是模板函数。你应该专业化整个班级。
Your constructor is not a template function. You should specialize the whole class.
这篇关于专门构建类模板构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!