c++ - 模板中定义类型未知的函数
天蓬老师
天蓬老师 2017-04-17 15:18:49
0
1
592

请问如何在一个模板中定义类型未知的函数呢?
我需要将一段程序的多个步骤和其中的某个操作分离,比如说:

#include <iostream>

template <typename T>
T adder(T a, T b)
{
    return a + b;
}

template <T F(T, T)>    //--- Here
T executor(T a, T b)
{
    return F(a, b);
}

int main()
{
    std::cout << executor<adder>(1, 2);
    std::cout << executor<adder>(3.0f, 4.0f);
    return 0;
}

但是上面template <T F(T, T)>中的T是不能被编译器识别的,怎样解决这个问题呢?

我自己找到答案了,这个贴就让沉掉吧(不知道怎么关闭╮(╯▽╰)╭):

#include <iostream>

template <typename T>
T adder(T a, T b)
{
    return a + b;
}

template <typename T, T F(T, T)>
T executor(T a, T b)
{
    return F(a, b);
}

int main()
{
    std::cout << executor<int, adder>(1, 2);
    std::cout << executor<float, adder>(3.0f, 4.0f);
    return 0;
}
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
刘奇

Here you must first determine the type of adder before you can infer the type of executor. The type of adder in the source program is determined by the function parameters of the executor. There is a problem in deriving the sequence, so it can be solved by manually giving the adder type. Surely maybe there is a better way?

#include <iostream>

template <typename T>
T adder(T a, T b)
{
    return a + b;
}

template <typename T, T F(T, T)>
T executor(T a, T b)
{
    return F(a, b);
}

int main()
{
    std::cout << executor<int, adder>(1, 2);
    std::cout << executor<float, adder>(3.0f, 4.0f);
    return 0;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template