C++:有没有一种简单的方法可以使用命名空间作为模板?[复制]

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

提问人:Shoam 提问时间:10/11/2022 最后编辑:Vlad from MoscowShoam 更新时间:10/11/2022 访问量:69

问:

有没有办法将命名空间用作模板? 我需要调用相同的函数,但从不同的命名空间。

类似的东西: 这里有两个命名空间,它们包含一个同名的函数 -myNamespace1, myNamespace2func()

#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;

}
C++ 模板 命名空间 template-classes

评论

3赞 Some programmer dude 10/11/2022
不。你想做什么?您需要解决的实际和根本问题是什么?请直接询问,否则您的问题将成为 XY 问题

答:

0赞 lorro 10/11/2022 #1

您可以创建标签类:

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;
1赞 Vlad from Moscow 10/11/2022 #2

命名空间不能用作模板参数。但是,例如,您可以使用非类型模板参数来表示函数,例如

#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();
}

程序输出为

myNamespace1
myNamespace2