Reputation: 769
I have a problem with the usage of a static class member size
of a class SizeObj
, which is used as template parameter for a template class SizeTemplate
. See below the code snippet, which I reduced to the minimum.
In fact that code below ran well up to MS VS2008, but now the compilation fails when compiling with VS2010. The following error messages are displayed:
error C2275: 'K' : illegal use of this type as an expression
error C2228: left of '.size' must have class/struct/union
It need to be said, that the compilation fails only, if the getSize
method is
called at least once.
Please don't ask about the sense of the code below, as said I reduced it to the essential minimum to explain. However, I need to admit that the usage of the member 'size' is not very elegant due to several reasons, and maybe there are lots of better solutions, but at the moment, I don't have any choice to keep it like that.
Do you know what may be wrong here? Is it possible to solve that by build settings or something similar? I didn't find yet anything suitable yet.
In the following posts it was easy, because an instance of class K is available, but for my problem, I don't know how to get that instance properly:
//myTemplate.h
class SizeObj
{
public:
static const int size = 1;
};
template<class K>
class SizeTemplate
{
public:
int getSize();
};
template<class K>
int SizeTemplate<K>::getSize()
{
return K.size;
}
//main.cpp
int main(...)
{
SizeTemplate<SizeObj> sizeObj;
printf("size:%d", sizeObj.getSize());
}
Thank you a lot in advance!
tangoal
Upvotes: 1
Views: 3918
Reputation: 21560
Unlike Java, in C++ you cannot use the dot operator on classes, you need use the scope resolution operator (i.e. ::
) to get things from within the class scope (for example the size
static variable), so replace return K.size
with return K::size
Also marking the method to be constexpr
is likely going to help here.
Upvotes: 2