gpt4 book ai didi

c++ - 使用模板模板参数的模板参数

转载 作者:太空狗 更新时间:2023-10-29 23:30:04 26 4
gpt4 key购买 nike

我目前正在使用 C++ 中的 template 并被 template template parameters 困住了。

假设我有以下类(class):

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() { }
};

本质上,我想要一个静态类,比如MyHub,它接受MyInterface 的实现并提供特定的static 方法来使用它们,例如 static T Foo()

然后我尝试使用 MyHub:

int main()
{
int i = MyHub<MyImpl>::Foo();

return 0;
}

不幸的是,我总是得到一个错误,指出类型 T(属于 MyHub 中的 static T Foo())没有命名类型。

我希望它能起作用,因为

  • 模板参数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;
}

Here是一个例子。

关于c++ - 使用模板模板参数的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32372916/

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