【发布时间】:2012-05-25 10:27:17
【问题描述】:
我知道这在 C++03 中是不可能的,但我希望有一些新的巫术可以让我做到这一点。见下文:
template <class T>
struct Binder
{
template<typename FT, FT T::*PtrTomember>
void AddMatch();
};
struct TestType
{
int i;
};
int main(int argc, char** argv)
{
Binder<TestType> b;
b.AddMatch<int,&TestType::i>(); //I have to do this now
b.AddMatch<&TestType::i>(); //I'd like to be able to do this (i.e. infer field type)
}
在 C++11 中有没有办法做到这一点? decltype 会有帮助吗?
** 更新:使用 Vlad 的示例,我在想这样的事情会起作用(警告:我没有编译,因为我现在正在构建具有 decltype 支持的编译器)
template <class T>
struct Binder
{
template<typename MP, FT ft = decltype(MP)>
void AddMatch()
{
//static_assert to make sure MP is a member pointer of T
}
};
struct TestType
{
int i;
};
int main()
{
Binder<TestType> b;
b.AddMatch<&TestType::i>();
}
这行得通吗?
【问题讨论】:
-
鉴于您明确指定它,我怀疑是否有办法。如果它是
AddMatch(&TestType::i),它甚至应该在 C++03 中工作。 -
您需要对指向成员的指针做什么?可能有比使用指向成员的指针作为非类型模板参数更好的解决方案。
标签: c++ templates c++11 decltype member-pointers