我目前正在尝试使用一种特殊的模板。这是一个非常小的示例,可以准确显示出了什么问题。 这是模板:
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>();
^
最佳答案
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);
}
};
关于android - C++ - 具有类函数引用的模板无法在 Android 上编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34407605/