我有以下代码:
template<typename T1, typename T2, typename T3, typename T4>
void Func(void); // signature
具有 4 个模板参数的简单模板函数。 this的用法目前是这样的:
Func<Foo1, Foo1Helper, Foo1Client, Foo1Server>();
Func<Foo2, Foo2Helper, Foo2Client, Foo2Server>();
Func<Foo3, Foo3Helper, Foo3Client, Foo3Server>();
现在在使用示例中,Foo1Helper, Foo1Client, Foo1Server, Foo2Helper, Foo2Client, Foo2Server, Foo3Helper, Foo3Client, Foo3Server
都是基于Foo1, Foo2, Foo3
生成的类> 类(class)。
我想要实现的是简化 Func
模板化函数,以便可以像这样调用它:
Func<Foo1>();
不需要指定生成的类,因为类的名称绑定(bind)到原始类。
您对我如何实现这一点有什么建议吗?
最佳答案
generated classes 的含义并不完全清楚,但您可以为它们提供一个元函数:
// declare metafunctions
template <typename T>
struct Helper;
template <typename T>
struct Client;
template <typename T>
struct Server;
// provide implementations
template <>
struct Helper<Foo1>
{ using type = Foo1Helper; };
template <>
struct Client<Foo1>
{ using type = Foo1Client; };
template <>
struct Server<Foo1>
{ using type = Foo1Server; };
// the same for Foo2, Foo3, etc
然后在 Func
中使用它们:
template <typename T>
void Func()
{
using THelper = typename Helper<T>::type;
using TClient = typename Client<T>::type;
using TServer = typename Server<T>::type;
}
关于c++ - 减少彼此紧密关联的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49734780/