g++不会让我将模板参数传递给 offsetof

发布于 2024-10-23 17:52:05 字数 514 浏览 1 评论 0原文

使用 g++ 时,我将模板参数作为成员变量传递给 offsetof,并收到以下警告:

invalid access to non-static data member 'SomeClass::t' of NULL object
(perhaps the 'offsetof' macro was used incorrectly)

这是我的用法:

template<typename T> class SomeClass { T t; };
...
offsetof(SomeClass, t); //warning: invalid access to non-static data member 'SomeClass::t' of NULL object, (perhaps the 'offsetof' macro was used incorrectly)

使用 __builtin_offsetof 时出现相同的错误。有什么想法吗?

谢谢

When using g++ I pass a template parameter as the member variable to offsetof, and I get the following warning:

invalid access to non-static data member 'SomeClass::t' of NULL object
(perhaps the 'offsetof' macro was used incorrectly)

Here is what my usage looks like:

template<typename T> class SomeClass { T t; };
...
offsetof(SomeClass, t); //warning: invalid access to non-static data member 'SomeClass::t' of NULL object, (perhaps the 'offsetof' macro was used incorrectly)

I get the same error using __builtin_offsetof. Any ideas?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰火雁神 2024-10-30 17:52:06

成员数据必须是公共的,因此使用 public 或 struct

template <typename T>
class SomeClass {
public:
    T t;
};
...
offsetof(SomeClass<double>, t);

请注意,预处理器总是尝试以逗号分隔参数,因此使用 typedef 作为解决方法。

#include <cstddef>

template <typename T1, typename T2>
class SomeClass {
public:
    T1 t1;
    T2 t2;
};

int main(int,char**) {
    typedef SomeClass<double, float> SomeClassDoubleFloat;
    offsetof(SomeClassDoubleFloat, t2);

    return 0;
}


编辑:抱歉,我误解了你的问题,所以我更改了答案 + lt & GT

Member data must be public, so use public or struct

template <typename T>
class SomeClass {
public:
    T t;
};
...
offsetof(SomeClass<double>, t);

Note that preprocessor alway try to split arguments at a comma, so use a typedef as a workaround.

#include <cstddef>

template <typename T1, typename T2>
class SomeClass {
public:
    T1 t1;
    T2 t2;
};

int main(int,char**) {
    typedef SomeClass<double, float> SomeClassDoubleFloat;
    offsetof(SomeClassDoubleFloat, t2);

    return 0;
}


edit: sorry, I misunderstood your question, so I have changed the answer + lt & gt

热风软妹 2024-10-30 17:52:06

这里有同样的问题,offsetof 不适用于模板类。

作为解决此问题的快速技巧,只需创建该类型的虚拟对象,并通过减去地址来计算偏移量:

SomeClass<int> dummy ;
const size_t offset =  ( (char*)(&dummy.t) ) - ( (char*) &dummy ) ; 

Had the same problem here, offsetof doesn't work with templated classes.

As a quick hack to solve this, just create a dummy object of that type, and calculate the offset by subtracting adresses:

SomeClass<int> dummy ;
const size_t offset =  ( (char*)(&dummy.t) ) - ( (char*) &dummy ) ; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文