如何“传递”命名空间作为参数?

时间:2018-10-17 10:10:27

标签: c++ namespaces

如果我有以下代码:

void foo1()
{
    NS1::Type1 instance1;
    NS1::Type2 instance2;
    NS1::Type3 instance3;
}

void foo2()
{
    NS2::Type1 instance1;
    NS2::Type2 instance2;
    NS2::Type3 instance3;
}

如何分解该函数?

我可以从NS1调用foo1,从NS2调用foo2。

1 个答案:

答案 0 :(得分:5)

  

如何“传递”命名空间作为参数?

没有办法做到。

如果使用类而不是名称空间,则可以为foo编写可重用的模板:

struct NS1 {
    using Type1 = int;
    using Type2 = float;
    using Type3 = std::string;
};

struct NS2 {
    using Type1 = long;
    using Type2 = double;
    using Type3 = std::string;
};

template<class T>
void foo() {
    typename T::Type1 instance1;
    typename T::Type2 instance2;
    typename T::Type3 instance3;
}