Can I use logical operators with function parameters?

advertisements

I want to create a function, where you can either use an int or a string variable as an parameter, but I don't know how.

I am writing a little example of what I want to achieve:

#include <iostream>
#include <string>

using namespace std;

int function((int a) || (string a))
{
    ...;
}

int main()
{
    int intvar;
    string stringvar;

    function(intvar);
    function(stringvar);
    return 0;
}


Can I use logical operators with function paramenters?

No, you can't.

What you basically want is a function template or overload. The latter is the simplest way:

int function(int a)
{
    // ...;
}

int function(string a)
{
    // ...;
}

In case you have the same code for the varying types use a template:

template<typename T>
int function(T a)
{
    static_assert(std::is_convertible<T,int>() || std::is_convertible<T,std::string>());
    // ...;
}