Why can't member functions be used as template arguments?

Why can't member functions be used as template arguments? For example, I want to do this:

struct Foo {
    void Bar() { // do something
    }
};
template <typename TOwner, void(&func)()>
void Call(TOwner *p) {
    p->func();
}
int main() {
    Foo a;
    Call<Foo, Foo::Bar>(&a);
    return 0;
}

I know that this can be done using member pointers; OK, this is cool enough most of the time, but I'm just wondering why pointers should be used.

I do not see the ambiguity of the interpretation of "p-> func ()" above. Why does the standard forbid us to use member functions as template arguments? Even static member functions are not allowed according to my compiler (VC ++ 2013). Does anyone know the reason? Or is there a way to do the same without losing any performance due to pointer dereferencing?

Thank.

+4
2

,

struct Foo {
    void Bar() { // do something
    }
};
template <typename TOwner, void(TOwner::*func)()>
void Call(TOwner *p) {
    (p->*func)();
}
int main() {
    Foo a;
    Call<Foo, &Foo::Bar>(&a);
    return 0;
}
+15

, - ( , ):

struct A
{
    int f(float x);
};

template <int (A::F*)(float)>
struct B {};

template<A *> struct C;
template<A &> struct D;

, ++, .

[temp.param]

  1. , , ( cv-) :

(4.1) - ,

(4.2) - ,

(4.3) - lvalue lvalue ,

(4.4) - ,

(4.5) - std:: nullptr_t.



, - , , a std::function object: -, . .

, . :

template<typename T, typename F>
void call(T&& t, F&&f)
{
    f(std::forward<T>(t));
}

struct A
{
    void foo() { std::cout<<"hello"<<std::endl; }  
};

int main()
{
    A a;
    auto f=std::bind(&A::foo, a);   //or possibly "std::ref(a)" instead of "a"
    call(3,f);
}

DEMO

0

All Articles