c++ - 减少彼此紧密关联的模板参数

标签 c++ templates traits

我有以下代码:

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/

相关文章:

c++ - 在 Linux 上管理共享库的常用方法是什么?

c++ - 应用世界变换

php - 我可以覆盖消费者类中的 PHP 特征属性以使用 Doctrine2 注释吗?

Scala 初始化行为

C++ 否定和重载决议

C++ 内存管理和 Misra

c++ - 简单引用计数 : smart pointers

c++ - 处理值和引用语义的模板类

c++ - 在模板函数 C++ 中的 F&&,Args &&... 参数之后添加另一个函数作为参数

Rust 在泛型类型参数上调用 trait 方法