我正在尝试创建一个可以具有由模板参数控制的函数和成员的类。我在想这样的事情。
template<int control>
class ControlledDeclaration
{
public:
if(1 == control)
int Get() { return 0; }
else if(2 == control)
char* Get() { return "get"; }
else if (3 == control)
bool Get() { return true; }
};
void test_template()
{
ControlledDeclaration<1> c_int;
ControlledDeclaration<2> tx_int;
ControlledDeclaration<3> b_int;
}
如果可以,怎么做?
最佳答案
我将使用的方法是专门化特征类中的细节并使用模板提供接口(interface)。在这个简单的示例中,使用特征而不是专门化实际类型并没有太多好处,但一般来说,使用特征比专门化更容易定制几个变体点。
template <int> struct ControlDeclarationTraits;
template <>
struct ControlDeclarationTraits<1> {
typedef int type;
static int value() { return 0; };
};
template <>
struct ControlDeclarationTraits<2> {
typedef char const* type;
static char const* value() { return "get"; }
};
template <>
struct ControlDeclarationTraits<3> {
typedef bool type;
static bool value() { return true; }
};
template<int control>
class ControlledDeclaration
{
public:
typename ControlDeclarationTraits<control>::type Get() {
return ControlDeclarationTraits<control>::value();
}
};
顺便说一句,字符串文字的类型是char const[n]
(对于合适的n
)而不是char[n]
,也就是说,您不能真正使用字符串文字来初始化 char*
。它确实有效,因为它被认为有必要支持现有代码将字符串文字分配给 char*
但它实际上是一个谎言:尝试为任何值分配一个值会导致未定义的行为。将指针设置为 const
可以清楚地表明内容不应该被修改。
关于c++ - 是否可以在模板类中有条件地声明方法和变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17979969/