c++ - 模板中定义类型未知的函数

查看:153
本文介绍了c++ - 模板中定义类型未知的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

#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;
}

解决方案

在这里首先要确定好adder的类型,才能推到出executor的类型。而源程序中adder的类型是由executor的函数参数确定的,推导先后次序出了问题,所以可以通过手动给出adder类型的方法解决。当然也许有更好的方法?

#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;
}

这篇关于c++ - 模板中定义类型未知的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆