c++ 模版类调用不同函数

我们都知道,c++ 用模版,可以根据不同的对象类型,生成不同的实际函数,但是,如果我想根据不同的条件,在一个模版类里面,调用不同的函数呢,能不能这样写

#include <iostream>

using namespace std;

void PrintA(int a)
{
    cout<<a<<endl;
}

void PrintB(int b)
{
    cout<<b<<endl;
}

template<class F, class V>
void Call(V i)
{
    F(i);
}

int main()
{
    Call<PrintA, int>(1);
    Call<PrintB, int>(2);
    return 0;
}

遗憾的是,这东西连编译都编译不过,上网查了一下,也没发现有类似的讨论。。

4 thoughts on “c++ 模版类调用不同函数

  1. 查了一下,发现这里有讨论,http://stackoverflow.com/questions/1174169/function-passed-as-template-argument

  2. C++的作法是用“函数对象”,重写()操作符.

    class PrintA
    {
    public:
    void operator()(int a)
    {
    cout<<a<<endl;
    }
    };
    call函数的模板里再稍微改一下:
    F f; // 实例化函数对象
    f(i);

    大多数情况下,不用C++模块能把代码写得更干净.

Leave a Reply to ZRJ Cancel reply

Your email address will not be published. Required fields are marked *