开发者

Force template parameter to be a structure

I'm trying to do a base template class which parameter T must be a structure.

When I use a variable declared as being of type T (both in the template class as in a class that extends it defining T) GCC fails to compile it:

GCC error: invalid use of incomplete type ‘struct x'

Despite it working on VC I understand that it doesn't work because it shouldn't because the compiler isn't aware per the standard of the types that T represent.

Is there a way of making explicit that the type must be a structure?

What I'm doing in the code that works in VC is:

In the base class:

T* x
new T
sizeof(T)

In those that extend 开发者_运维知识库it:

x->member

Edit: I tried to take the relevant code. Here it is:

struct SomeStructureType
{
    int memberA;
    int memberB;
}

template <typename T> class Base
{

    protected:

        T* s;

        void addMember(string name,void* offset);

        Base()
        {
            s = new T;
        }

};

class Extender : public Base<SomeStructureType>
{
    public:

        Extender()
        {
            addMember("memberA",&s->memberA);
        }
}


Most (if not all) times the compiler complains about using an 'incomplete' type the problem resides in trying to use a forward declared class that has not been completely defined.

There are just so many things you can do with an incomplete type: define functions that take or return the type or references to it, define reference or pointer variables of that type... and others you cannot do: define variables of that type, create an object of the type, call any method or request any attribute from the type...


The question in the title can be dismissed; C++ classes and structures cannot be distinguished other than by source code inspection.

The explanation is quite confusing. There's apparently a message about struct x yet the example code contains not a single x. That tells me that you're not careful about matching up errors and source code. Once you do that, you often don't need StackOverflow anymore - you'll see the problem yourself.


There is nothing wrong with the code you've posted other than two missing semicolons after class/struct definitions: http://codepad.org/yfbHa8sO


The problem isn't related to the fact that T must be a structure. The problem is in that one of the structures (that I'm using in my code but was not created by me) is said to be incomplete by gcc. Anyway, I removed the class that uses this structure and other classes compile with the same base class. So, is up to me to fix it and what I assumed about the problem was wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜