David Meléndez
David Meléndez

Reputation: 411

c++ Import two functions with the same name and parameters from different files

Let's suppose I have a function named the same and with the same parameters in two different files that I want to import to my main.

void foo(int a)
{
    // Some code, this function in file A
}

void foo(int a)
{
    // Some code, this function in file B
}

How can I do it?

If it is possible, how could the compiler differentiate between the two functions?

Upvotes: 1

Views: 800

Answers (2)

TheEagle
TheEagle

Reputation: 5982

The simplest way is to use namespaces:

filea.hpp

namespace a {
    inline void foo(int a) {
        // Some code, this function in file A
    }
}

fileb.hpp

namespace b {
    inline void foo(int a) {
        // Some code, this function in file A
    }
}

main.cpp

#include "filea.hpp"
#include "fileb.hpp"
int main() {
    a::foo(1);
    b::foo(1);
    return 0;
}

Upvotes: 3

Kanony
Kanony

Reputation: 539

enum class file {
    A, B
};

void foo(int a, file f) {
    if(f == file::A) {
        // Do some stuff for A
    }else{
        // Do some stuff for B
    }
    
}

Or just declare them in different namespaces

Upvotes: 1

Related Questions