我目前template
在C ++中玩s并受困于template template parameters
。
可以说我有以下课程:
template<typename T>
struct MyInterface
{
virtual T Foo() = 0;
}
class MyImpl : public MyInterface<int>
{
public:
int Foo() { /*...*/ }
};
template< template<typename T> typename ImplType>
class MyHub
{
public:
static T Foo()
{
ImplType i;
return i.Foo();
}
private:
MyHub() { }
~MyHub() { }
};
本质上,我希望有一个static class
like MyHub
,它可以接受of的实现MyInterface
并提供某些static
方法来使用like static T Foo()
。
然后我尝试使用MyHub
:
int main()
{
int i = MyHub<MyImpl>::Foo();
return 0;
}
不幸的是,我总是最终得到一个错误,指出T
(static T Foo()
在MyHub中的)类型没有命名类型。
我希望它能起作用,因为
Impl
名为TMyHub
是具有一个模板参数的模板化类,并包含一个方法 Foo
到目前为止,在浏览了文档和Google搜索结果之后,我找不到针对此问题的解决方案,因此希望你们中的一些人能对我有所帮助。
您可以使用typedefs。另外,由于您的实现类不是模板类,因此不需要模板模板参数。
#include <iostream>
#include <string>
template<typename T>
struct MyInterface
{
virtual T Foo() = 0;
typedef T Type;
};
class MyIntImpl : public MyInterface<int>
{
public:
int Foo() { return 2; }
};
class MyStringImpl : public MyInterface<std::string>
{
public:
std::string Foo() { return "haha"; }
};
template<class ImplType>
class MyHub
{
public:
static typename ImplType::Type Foo()
{
ImplType i;
return i.Foo();
}
private:
MyHub() { }
~MyHub() { }
};
int main()
{
std::cout << MyHub<MyIntImpl>::Foo() << "\n"; // prints 2
std::cout << MyHub<MyStringImpl>::Foo() << "\n"; // print haha
return 0;
}
这是一个例子。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句