[英]Accessing public static members of a templated class without instantiating the template?
I have a templated class and want to access a public static variable from outside it, but I can't figure out any way to do so without instantiating the template. 我有一个模板化的类,并希望从外部访问一个公共静态变量,但我不知道如何在不实例化模板的情况下这样做。 This code:
这段代码:
template<class T>
class TemplatedClass {
public:
static const int static_member = 10;
};
... ...
int i = TemplatedClass::static_member;
Produces the following error: "'template class TemplatedClass' used without template parameters." 产生以下错误:“'模板类TemplatedClass'在没有模板参数的情况下使用。”
If I instantiate the class when accessing the variable: 如果我在访问变量时实例化该类:
int i = TemplatedClass<int>::static_member;
The error goes away. 错误消失了。 I would prefer not to have to instantiate a template in a context where it doesn't really make sense with a dummy type argument just to suppress an error.
我宁愿不必在一个上下文中实例化一个模板,它只是为了抑制错误而使用虚拟类型参数没有意义。 If I have to, what would be the best dummy type to use?
如果必须的话,最好使用哪种假型? I tried <> and <void>, but neither worked.
我试过<>和<void>,但都没有用。
Can't be done, since specializations might override the value, ie: 无法完成,因为专业化可能会覆盖该值,即:
template<class T>
class TemplatedClass : public BaseClass
{
static const int value = 42;
};
template<>
class TemplatedClass<StarTrek>
{
static const int value = 47;
}
Thus you will get different values: 因此,您将获得不同的值:
TemplatedClass<StarTrek>::value != TemplatedClass<void>::value
If the values are to be equal, I strongly suggest you add a non-template base class: 如果值相等,我强烈建议您添加非模板基类:
class BaseClass {
public:
static const int value = 42;
};
template<class T>
class TemplatedClass : public BaseClass
{
...
}
Instantiating or explicitly a dummy type (ie void) might work, but you might get compile errors depending on how you use your template parameter. 实例化或显式虚拟类型(即void)可能有效,但您可能会遇到编译错误,具体取决于您使用模板参数的方式。
int x = TemplatedClass<void>::value;
So, please write code which show your intentions clearly, ie common values for all instantiations should not be in the type-dependent template class. 因此, 请编写清楚显示您的意图的代码,即所有实例化的常见值不应位于依赖于类型的模板类中。 If you can't have that, please explain what you're trying to do in more detail.
如果你不能那样做,请详细解释你想要做的事情。
Using a dummy type might work for trivial classes, but not if things get more complex. 使用虚拟类型可能适用于普通类,但如果事情变得更复杂则不行。
Let's imagine, that your class "continues" like this: 让我们想象一下,你的班级“继续”如下:
template<class T>
class TemplatedClass {
public:
static const int static_member = 10;
typedef typename std::enable_if< std::is_integral< T >::value >::type type;
};
This code tells us that T cannot be non-integral type. 这段代码告诉我们T 不能是非整数类型。
Upd (thanks to jogojapan): That's why in some cases you cannot use any type as a dummy one Upd(感谢jogojapan):这就是为什么在某些情况下你不能使用任何类型作为虚拟类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.