Search code examples
c++templatesc++11decltypemember-pointers

Is there anyway in C++11 to get member pointer type within a template?


I know this was not possible in C++03, but I'm hoping there is some new voodoo to allow me to do this. See below:

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)
}

Is there any way to do this in C++11? Will decltype help?

** UPDATE: Using Vlad's example I Was thinking something like this would work (caveat: I have not compiled as I am building the compiler with decltype support now)

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>();  
}

Would this work?


Solution

  • What you are trying to do cannot be done, that is, you cannot use a member pointer as a constant expression unless you have a type. That is, the type of a non-type template argument must be provided, or in other words, there is no type inference for template arguments.