gpt4 book ai didi

c++ - 基于模板参数的动态命名空间使用

转载 作者:可可西里 更新时间:2023-11-01 18:37:05 26 4
gpt4 key购买 nike

我不知道这是否可行,但这是我想要实现的:在模板化类中,我想使用模板参数的命名空间。

例如。

template<class P>
class Foo
{
public:
Foo();
virtual ~Foo();

void doSomething(P&);
void doSomethingElse();

protected:
// There I'm hardcoding "namespace1" but that's what I'd like to
// be possibly dynamic
// (I'm assuming template parameter P = namespace1::Type)
void method1(namespace1::Type1&);
...
void methodN(namespace1::TypeN&);
}

// Again, supposing P == namespace1::Type then I want to be using namespace1
// everywhere in the implementation...
using namespace namespace1;

template<class P>
void Foo<P>::doSomething(P& parameter)
{
...
Type1 type1 = P.getType1(); // There namespace1::Type1 is returned !!
method1(type1);
...
}

template<class P>
void Foo<P>::doSomethingElse()
{
...
TypeN typen; // There I want to instanciate a namespace1::TypeN !!
...
}

...

当然,我不想专门化模板并为每个可能的 P 值提供专门的实现,而且我想避免传递所有类型,如 Type1TypeN 作为模板参数,因为我可能有很多。

这可能吗?

该项目基于 C++3,欢迎使用任何 boost 解决方案。

更新

作为模板参数 P 本身与任何 TypeN 参数完全一样,这可能是正确的方法:

template<typename NAMESPACE>
class Foo
{
typedef typename NAMESPACE::Parameter MyParameter;
typedef typename NAMESPACE::Type1 MyType1;
typedef typename NAMESPACE::Type1 MyTypeN;
...
}

最佳答案

是和否

是的,可以从主要类型推断次要类型,通常使用特征系统:

template <typename T> struct Trait { typedef typename T::Secondary Secondary; };

template <typename X>
struct Foo {
typedef typename Trait<X>::Secondary Secondary;

void foo(Secondary const& s);
};

不,您不能推导出命名空间,因此不能使用;但请注意如何在类中使用本地别名 (typedef ...) 就没有必要了。

关于c++ - 基于模板参数的动态命名空间使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15026092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com