在c ++中重用具有不同可能类型的参数的函数调用

时间:2017-03-02 15:55:02

标签: c++ templates

我想知道是否有办法在以下c ++代码中重用对函数template_fun的调用。

#include <iostream>
#include <cstdlib>
#include <ctime>


template <typename T>
double template_fun(T arg)
{
    double a = 1.1;
    a += (double)arg;
    return a;
}

int main()
{
    std::srand(std::time(0));
    int r = std::rand() % 2;
    double out;

    switch(r)
    {
        case 0:
        {
            int arg = 1;
            out = template_fun(arg);
            break;
        }
        case 1:
        {
            double arg = 1.2;
            out = template_fun(arg);
            break;
        }
    }

    std::cout << out << "\n";
}

由于重复了out = template_fun(arg);行,我希望有办法以某种方式重用它。显然,根据输入调用具有不同输入数据类型的模板函数的问题实际上是我所得到的。我正在处理的代码要复杂得多。我并不特别希望有一个聪明的解决方案,因为它可能意味着在运行时定义arg的数据类型。但也许我错过了一些东西。

提前感谢您的帮助!非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用某些variant课程,并执行以下操作:

struct template_fun : boost::static_visitor<double>
{
    template <typename T>
    double operator() (T arg) const
    {
        double a = 1.1;
        a += (double)arg;
        return a;
    }
};

int main()
{
    std::srand(std::time(0));
    int r = std::rand() % 2;
    boost::variant<int, double> arg;
    double out = 0.0;

    switch(r)
    {
        case 0: { arg = 1;   break; }
        case 1: { arg = 1.2; break; }
    }
    out = boost::apply_visitor(template_fun{}, arg);
    std::cout << out << "\n";
}

Demo