【发布时间】:2018-01-19 21:59:10
【问题描述】:
我有两个不同的命名空间,它们以两种不同的方式实现相同的方法和类。我正在编写一个使用这些方法和类来做某事的类,我想知道是否有一种方法可以在没有部分特化的情况下声明命名空间,如下所示:
#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' 没有在这个范围内声明
【问题讨论】:
-
using namespace不允许在类范围内。 -
@Jaa-c。我知道,这段代码只是我需要的演示,有解决方法吗?
-
这看起来像an XY problem。你想用这样的解决方案解决什么真正的问题?
-
@Someprogrammerdude:这实际上是我想要解决的一个真正的问题,我有一个为系统套接字提供接口的类,该套接字的另外三个实现在不同的命名空间中提供了类似的方法,如果我能做这样的事情,我就能将所有的类简化为一个并维护一个代码
-
@apramc:我能想到的最好的方法是像
static constexpr auto test = &one::test;这样向继承的类添加一个成员,而不是在delcare_namespace中调用this->test()。但是没有办法在类范围内以某种方式使用命名空间或声明命名空间别名。
标签: c++ c++11 templates template-meta-programming template-specialization