1

Is there a way to use a namespace as a template? I need to call the same function but from a different namespaces.

Something like that: There are two namespaces here myNamespace1, myNamespace2 that contain a function with the same name - func()

#include <iostream>

using namespace std;

namespace myNamespace1 {
    void func()
    {
        std::cout<<"myNamespace1" << std::endl;
    }
}

namespace myNamespace2 {
    void func()
    {
        std::cout<<"myNamespace2" << std::endl;
    }
}

  template<auto T>
  class A {
  public:
    void func()
    {
        T::func();
    }
  };
}


int main() {
  using namespace myNamespace1;
  using namespace myNamespace2;

  A<myNamespace1> a1;
  a1.func(); // output: myNamespace1
  
  A<myNamespace2> a2;
  a2.func(); // output: myNamespace2
  
  return 0;

}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Shoam
  • 25
  • 2
  • 3
    No. What are you trying to do? What is the actual and underlying problem you need to solve? Please ask about that directly, otherwise your question becomes an [XY problem](https://xyproblem.info/). – Some programmer dude Oct 11 '22 at 12:47

2 Answers2

1

A namespace may not be used as a template parameter. But you can use for example a non-type template parameter that denotes a function like for example

#include <iostream>

namespace myNamespace1 {
    void func()
    {
        std::cout << "myNamespace1" << std::endl;
    }
}

namespace myNamespace2 {
    void func()
    {
        std::cout << "myNamespace2" << std::endl;
    }
}

template<void ( &Func )()>
class A {
public:
    void func()
    {
        Func();
    }
};

int main()
{
    A<myNamespace1::func> a1;

    a1.func();

    A<myNamespace2::func> a2;

    a2.func();
}

The program output is

myNamespace1
myNamespace2
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You can create tag classes:

class myNamespace1Tag {};
class myNamespace2Tag {};

template<typename T>
using A_in = std::conditional_t<std::is_same_v<T, myNamespace1Tag>, myNamespace1::A, std::conditional_t<std::is_same_v<T, myNamespace2Tag>, myNamespace2::A, void>;

A_in<myNamespace1Tag> a1;
lorro
  • 10,687
  • 23
  • 36