Search code examples
c++classtemplatesnamespacestemplate-classes

C++: Is there a simple way of using a namespace as template?


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;

}

Solution

  • 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