繁体   English   中英

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

[英]Reuse function call with argument of different possible types in c++

我想知道是否有一种方法可以在以下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的数据类型。 但是也许我错过了一些东西。

预先感谢您的帮助! 非常感激。

您可以使用一些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";
}

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM