简体   繁体   English

调用模板类成员时非法使用此类型作为表达式

[英]Illegal use of this type as an expression when calling template class member

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 . 我有一个类的静态成员的使用问题size的一类SizeObj ,这是作为一个模板类模板参数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. 实际上,下面的代码可以很好地运行到MS VS2008,但是现在使用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. 需要说的是,只有在至少调用一次getSize方法时,编译才会失败。

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. 但是,我需要承认,由于多种原因,成员“ size”的使用并不十分优雅,也许有很多更好的解决方案,但是目前,我别无选择。 。

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: 在以下帖子中,这很容易,因为可以使用类K的实例,但是对于我的问题,我不知道如何正确获取该实例:


//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 探戈

Unlike Java, in C++ you cannot use the dot operator on classes, you need use the scope resolution operator (ie :: ) to get things from within the class scope (for example the size static variable), so replace return K.size with return K::size 与Java不同,在C ++中,不能在类上使用点运算符,而需要使用范围解析运算符(即:: return K.size从类范围内获取内容(例如size静态变量),因此将return K.size替换为return K::size

Also marking the method to be constexpr is likely going to help here. 另外,将方法标记为constexpr可能会在这里有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM