【发布时间】:2012-05-21 04:26:52
【问题描述】:
我想定义一个空值静态模板成员函数,该函数将(明确)专门用于指向数据成员的指针,并且对于每个专门化,可能具有不同的返回类型。
它应该返回一些关于每个属性的详细信息,因此我将这个方法称为trait。返回的特征对象类型将被其他模板检查,因此整个机制必须在编译时可用。
到目前为止,我有这样的东西(当然是损坏的代码):
class Foo{
// some data members
int a; std::string b; int c;
// how to declare generic template here?
// compile-time error should ensue if none of the specializations below is matched
// specialization for a (aTraitExpr is expanded from macro, so it is OK to repeat it)
template auto trait<&Foo::a>()->decltype(aTraitExpr){ return aTraitExpr; }
// specialization for b; the return type will be different than for trait<&Foo::a>
template auto trait<&Foo::b>()->decltype(bTraitExpr){ return bTraitExpr; }
};
// some code which queries the trait at compile-time
// e.g. supposing all possible trait types declare isSerializable
// which happens to be True for a and False for b
Foo* foo;
template<bool isSerializable> void doSerialization(...);
template void doSerialization<true>(...){ ... };
template void doSerialization<false>(...){ /* no-op */ };
doSerialization<Foo::trait<&Foo::a>()::isSerializable>(...); // -> doSerialization<true>(foo)
doSerialization<Foo::trait<&Foo::b>()::isSerializable>(...); // -> doSerialization<False>(...)
doSerialization<Foo::trait<&Foo::c>()::isSerializable>(...); // -> compile error, specialization Foo::trait<&Foo::c> not defined
能得到一些关于如何实现这一点的提示吗? (我不是想发明一个新的序列化系统,我已经使用了 boost::serialization;每个 trait 中都会有更多信息,这只是一个示例,为什么在编译时需要它。
编辑:我能够得到接近我想要的东西,它显示为at ideone.com。我放弃了trait<Foo::a>()(现在),所以有一个静态函数getTrait_a(),它返回对可修改类型特征的引用,但在编译时部分固定(例如,Foo::TraitType_a::flags 工作)。感谢所有回复的人,很遗憾我只能选择其中一个作为“答案”。
【问题讨论】:
标签: c++ templates c++11 pointer-to-member