【问题标题】:C++ - Template with class function reference doesn’t compile on AndroidC++ - 带有类函数引用的模板无法在 Android 上编译
【发布时间】:2015-12-22 02:30:32
【问题描述】:

我目前正在尝试使用一种特殊的模板。这是一个非常简单的示例,可以准确显示出了什么问题。 这是模板:

template <typename ClassT,  int (ClassT::*Func)() const>
class TEST
{
public:
    TEST(ClassT const * selfVar) : _this(selfVar) {
    }

private:
    ClassT const* _this;
    };

这段代码是我项目的Entity.h文件:

int _a;
int getA() const {
    return _a;
}

TEST<TestClass, &TestClass::getA> test = TEST<TestClass, &TestClass::getA>(this);

该代码在带有 Xcode 的 iOS 上编译得很好,但在 Android 上却没有,并出现以下错误。无法在构造函数中进行初始化 - 我知道这可行,但我需要将其作为 .h 文件中的单行。

这是错误日志:

jni/../../Classes/Entity.h:37:54: warning: extra qualification 'Entity::' on member 'getA' [-fpermissive]
 TEST<Entity, &Entity::getA> yoyo = TEST<Entity, &Entity::getA>();
                                                  ^
jni/../../Classes/Entity.h:37:62: error: expected ';' at end of member declaration
 TEST<Entity, &Entity::getA> yoyo = TEST<Entity, &Entity::getA>();
                                                          ^
jni/../../Classes/Entity.h:37:62: error: 'TEST<Entity, &Entity::getA>& Entity::getA' conflicts with a previous declaration
jni/../../Classes/Entity.h:29:9: note: previous declaration 'int Entity::getA() const'
 int getA() const {
     ^
jni/../../Classes/Entity.h:37:66: error: expected unqualified-id before '>' token
 TEST<Entity, &Entity::getA> yoyo = TEST<Entity, &Entity::getA>();
                                                              ^
jni/../../Classes/Entity.h:37:45: error: wrong number of template arguments (1, should be 2)
 TEST<Entity, &Entity::getA> yoyo = TEST<Entity, &Entity::getA>();
                                         ^

【问题讨论】:

  • 可能我遗漏了什么,但是TEST的默认构造函数会被自动调用,= …中不需要。简单的 TEST&lt;Entity, &amp;Entity::getA&gt; test; 对我有用(如果你用 struct Entity {…}; 包装 Entity.h
  • 在这个最小的例子中你是对的,默认构造函数对于我的情况是不够的。我编辑了示例代码。你也知道如何解决这个案子吗?
  • TEST&lt;TestClass, &amp;TestClass::getA&gt; test (this); 也可以使用{this}

标签: android c++ ios android-ndk cocos2d-x


【解决方案1】:
template <typename ClassT,  int (ClassT::*Func)() const>
class TEST
{
public:
    TEST(ClassT const * selfVar) : _this(selfVar) {
    }

private:
    ClassT const* _this;
};

struct Entity {
    int _a;
    int getA() const {
        return _a;
    }
};

class TestClass: public Entity {
    void method() {
        TEST<Entity, &Entity::getA> test(this);
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多