简体   繁体   中英

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?

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;
}
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 namespace s

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