Tor*_*enJ 2 c++ templates c++17
我现在正在玩templateC++中的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() { }
};
Run Code Online (Sandbox Code Playgroud)
从本质上讲,我希望有一个接受实现的static class类似MyHub,MyInterface并提供某些static方法来使用它们static T Foo().
然后我试着用MyHub:
int main()
{
int i = MyHub<MyImpl>::Foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我总是得到一个错误,说明T(static T Foo()MyHub中的)类型没有命名类型.
我希望它有效,因为
Impl名为T.MyHub 是一个带有一个模板参数的模板化类,包含一个方法 Foo到目前为止,我在挖掘文档和谷歌搜索结果后找不到解决方案,所以我希望你们中的一些人可以帮助我.
您可以使用typedef.此外,由于您的实现类不是模板类,因此不需要模板模板参数.
#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;
}
Run Code Online (Sandbox Code Playgroud)
这是一个例子.