简体   繁体   English

从指针到成员的类模板推论

[英]class template deduction from pointer to member

As one of the class template parameters I need to use a pointer to member: 作为类模板参数之一,我需要使用一个指向成员的指针:

template <class Base, typename Member, Member Base::*m>
class MemPtrTestUgly
{
...
};

This needs to be used as 这需要用作

struct S
{
    int t;
}

MembPtrTestUgly <S, int, &S::t> m;

But I want to use it as this: 但我想这样使用它:

MemPtrTestNice<S, &S::t> m;

The member type is deduced from the member pointer. 成员类型是从成员指针推导出的。 I cannot use function template, as the MemPtrTest class is not supposed to be instantiated (there are just some static functions that will be used). 我不能使用函数模板,因为不应实例化MemPtrTest类(将使用某些静态函数)。 Is there a way how to do it in pure C++03 (no Boost or TR1)? 有没有办法在纯C ++ 03中做到这一点(没有Boost或TR1)?

You can use partial specialization and get a pretty nice-looking implementation: 您可以使用部分专业化,并获得一个漂亮的实现:

template <typename TMember, TMember MemberPtr>
class MemPtrTest;

template <typename TBase, typename TType, TType TBase::*MemberPtr>
class MemPtrTest<TType TBase::*, MemberPtr>
{
    // ...
};

This would be used as: 这将用作:

MemPtrTest<decltype(&S::t), &S::t> m;

Of course, this requires decltype or an equivalent, if you don't want to implicitly specify the member type. 当然,如果您不想隐式指定成员类型,则需要decltype或等效项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM