模板中的命名空间特化 class

namespace specialization in template class

我有两个不同的命名空间,它们以两种不同的方式实现相同的方法和 classes。我正在编写一个 class,它使用此方法和 classes 来做某事,我想知道是否有一种方法可以在不使用部分特化的情况下声明命名空间,如下所示:

#include <string>
#include <iostream>

namespace one
{
int test()
{
    return 1;
}
}

namespace two
{
int test()
{
    return 2;
}
}

enum names : int
{
    first = 1,
    second = 2
};

template <names>
struct base_class;

template <>
struct base_class<names::first>
{
    using namespace ::one;
};

template <>
struct base_class<names::second>
{
    using namespace ::two;
};

template <names ns>
struct delcare_namespace : public base_class<ns>
{
    delcare_namespace()
    {
        std::cout << test() << "\n";
    }
};

对于上面的代码,我得到

test’ was not declared in this scope

I was wondering if there was a way to declare the namespace

不幸的是,我认为在 class/struct 中并继承它是不可能的。

is there a work-around for this ?

我能想象的最好的(如果你可以大量修改你的代码)是将你的两个命名空间转换为两个不同的 classes 或结构,这样函数就变成了方法(可能是 static 方法)

struct baseOne  // former namespace one
 {
   static int test ()
    { return 1; }
 };

struct baseTwo // former namespace two
 {
   static int test ()
    { return 2; }
 };

因此您可以将基础 class(以前的命名空间)作为模板参数传递并从中继承

template <typename B>
struct foo : public B
 {
   foo ()
    { std::cout << B::test() << "\n"; }
 };

以下是完整的工作示例

#include <string>
#include <iostream>

struct baseOne  // former namespace one
 {
   static int test ()
    { return 1; }
 };

struct baseTwo // former namespace two
 {
   static int test ()
    { return 2; }
 };

template <typename B>
struct foo : public B
 {
   foo ()
    { std::cout << B::test() << "\n"; }
 };

int main ()
 {
   foo<baseOne> f1; // print 1
   foo<baseTwo> f2; // print 2
 }

如果在方法名称之前使用 B:: 对您来说很烦人,您可以将 static 方法转换为普通方法中的基础结构或添加指令为

using B::test;

里面 foo

using namespace 在 class 范围内不允许,命名空间别名也不允许。我不认为你可以做一个会以某种方式注入命名空间的专业化。

这并不完全相同,但如果可以选择在特化中从该名称空间声明您需要的所有函数,则可以将函数指针作为该特化的成员:

template <names>
struct base_class;

template <>
struct base_class<names::first>
{
    static constexpr auto test = &one::test;
};

template <>
struct base_class<names::second>
{
    static constexpr auto test = &two::test;
};

template <names ns>
struct delcare_namespace : public base_class<ns>
{
    delcare_namespace()
    {
        std::cout << this->test() << "\n";
    }
};