<分区>
这个问题不太可能帮助任何 future 的访问者;它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况有关,这些情况并不普遍适用于互联网的全局受众。为了帮助使这个问题更广泛地适用,
visit the help center .
关闭 10 年前 。
我在类中有一个非整数常量声明。
我不断收到以下信息:
ComponentClass.h:14: error: template declaration of const typename ComponentClass<T> ::position NULLPOSITION
ComponentClass.h:14: error: position was not declared in this scope
ComponentClass.h:14: error: expected ;
before numeric constant
请在下面找到我的代码。
组件类.h
#ifndef _ComponentClass_H
#define _ComponentClass_H
template< class T>
class ComponentClass
{
public:
typedef ComponentClass* position;
ComponentClass();
};
template<class T>
const typename ComponentClass<T>::position NULLPOSITION=(position)0;
template<class T>
ComponentClass<T>::ComponentClass(){}
#endif
您似乎在尝试定义一种“模板变量”,但 C++ 中不存在此类功能。
你也未能获得第二名的资格,你写了position
在同一行代码中。
这两个因素是导致你出错的原因。
它可能 对NULLPOSITION
有一些 意义成为类模板实例的静态成员:
template< class T>
class ComponentClass
{
public:
typedef ComponentClass* position;
static const position NULLPOSITION;
ComponentClass();
};
但是现在,据我所知,您必须为每个 T
定义它你想使用,这很糟糕:
template<>
const ComponentClass<int>::position ComponentClass<int>::NULLPOSITION =
static_cast<ComponentClass<int>::position>(0);
template<>
const ComponentClass<double>::position ComponentClass<double>::NULLPOSITION =
static_cast<ComponentClass<double>::position>(0);
也许改为 position
比单纯的指针类型更聪明一点——让它成为一个适当的用户定义类型,带有一个默认构造函数,将对象初始化为“空”状态。例如,函数对象以这种方式工作; std::function<void()>()
是一个有效但单一 的函数对象。