c++ functor and function templates

淺唱寂寞╮ 提交于 2019-11-30 11:24:39
Todd Gardner

There's not another "direct" way I know other than the:

 a.operator()<1>();

syntax. If you're open to changing the code, moving the template parameter to the class would work, or using a (boost|tr1)::bind to make a (boost|tr1)::function object.

You can only call

a.operator()<1>();

but that would not be using a functor. Functors need a non template operator(), as they must be able to be called as varname() and that won't work with your code.

To make it a real functor change your code a template class (functors are classes):

#include <iostream>

template<int N>
struct A {
    void operator()() {
        std::cout << N << std::endl;
    }
};

int main() {
    A<1> a;
    a();
}

You are trying to pass a template parameter to an instance of an object, which as far as I know is not allowed. You can only pass templates parameters to template functions or template objects.

a.test<1>(); and a.operator()<1>(); work because they are serving as template functions.

Use boost::bind (check out boost libraries) to fix it though.

struct A {
    void operator()(int n) {
        std::cout << n << std::endl;
    }
};

int main(int argc, char* argv[]) {
    A a;
    boost::function<void()> f = boost::bind<void>(a, 1);
    f(); // prints 1

    return 0;
}

And you don't even have to mess with templates!

You're stuck. Have you considered something like

struct A {
    template<int N>
    struct B
    {
        void operator()()
        { std::cout << N << std::endl; }
    };

    template<int N>
    B<N> functor() {return B<N>();}
};

int main()
{
    A a;
    a.functor<1>()();
}

Nope, there's no way around it. Like you said, you have to either call the operator explicitly (which defeats the purpose), or the template arguments must be able to be deduced by the compiler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!