我正在尝试做一些花哨的模板,我偶然发现了一个问题:我想在定义一个非静态成员时得到一个类的类型.这可能吗?(在任何C++版本中.)
请使用以下代码:
template<typename T>
struct inner {
T* this_;
/* fancy stuff... */
};
struct foo {
inner<foo> bar{this};
};
Run Code Online (Sandbox Code Playgroud)
该类foo有一个bar用指针初始化的非静态成员foo* this.这段代码用clang和gcc编译.
但我实际上希望定义inner出现在宏中,这意味着我没有foo在行中使用的字符串inner<foo> bar{this}.试图使用:
inner bar{this};
在C++ 17中,它允许对类模板进行模板参数推导,从而产生错误
错误:使用类模板'inner'需要模板参数; 非静态struct成员中不允许使用参数推导
inner bar{this};
我明白了 试:
inner<decltype(*this)> bar{this};
产生类似的错误:
错误:在非静态成员函数之外无效使用'this'
inner<decltype(*this)> bar{this};
作为一种解决方法,我一直在使用以下奇怪的重复模板模式:
template<typename T>
struct SelfAwareType {
using myOwnType = T;
}
struct foo : SelfAwareType<foo> {
inner<myOwnType> bar{this};
};
Run Code Online (Sandbox Code Playgroud) 我正在为objective-c编写一个xml序列化类.
关键是给类一个类类型和一个xml文件.它应该返回一个包含数据的实例.
我已经有了它的工作,它确实有很多 - 处理原语(+ nsstring),用户定义的类和nsarrays.不处理指针或C数组.
显然,这很大程度上依赖于反思.
问题:当我设置某个类的实例的值时,我应该检查是否存在具有正确名称的属性,还是可以使用简单的反射设置变量?
这是我到目前为止使用的那种代码:
id newClass = class_createInstance(NSClassFromString(elementName), sizeof(unsigned));
Ivar nameVar = class_getInstanceVariable([newClass class], "name");
if (nameVar != nil)
object_setIvar(newClass, nameVar, [NSString stringWithString:@"George"]);
Run Code Online (Sandbox Code Playgroud)
此外,在这种任务之后,我应该发布什么吗?