简体   繁体   中英

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

I am wondering if there is a way to reuse the call to the function template_fun in the following c++ code.

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

Since the line out = template_fun(arg); is repeated, I was hoping there was a way to reuse it somehow. Obviously, this issue of calling a template function with different input data types depending on an input is really what I'm getting at. The code I'm working on is much more complex. I am not particularly hopeful for a clever solution, since it would probably mean defining the data type of arg at runtime. But perhaps I am missing something.

Thank you in advance for your help! Much appreciated.

You may use some variant class, and do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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