使用模板模板参数的替代方案
Alternatives to using template template parameters
我目前使用一个具有多个参数的模板类,
template<class A, class B> class M{ };
然而,在类A
的位置上,我想插入一个模板类,类似
template<class C> class A{ };
我找到的唯一解决方案是使用模板模板参数:
template< template<class C> class A, class B> class M{ };
在我的实现中,我使用的A
的唯一参数化是A<B>
。我不需要使用不同参数对A
进行多次实例化,例如,我不需要在M
中实例化A<int>
、A<double>
和A<long double>
。
是否有模板模板参数的替代方案?我问的原因是这个帖子的后续内容,在他的回答中@Evan Teran说他只使用过一次模板参数。。。
我想我的问题有一个转折点:使用模板-模板参数有缺点吗?
假设B
可以从A<B>
中以某种方式确定,那么您只需要使用一个模板参数:
template <class A> class M
{
typedef typename A::The_B_Type B;
};
当然,The_B_Type
必须是A<B>
中的有效typedef。这就是标准库容器提供所有typedef的原因之一。例如,如果模板A
是std::vector
,则可以执行以下操作:
template <class A> class M
{
typedef typename A::value_type B;
};
您可以将实例化的A<B>
作为参数,然后使用traits类提取传递给A<B>
的B
(如果需要):
template<typename T>
struct extract_b {}; // SFINAE enabled
template<template<class>class A, typename B>
struct extract_b< A<B> > {
typedef B type;
};
// C++11, you can replace it with typename extract_b<T>::type at point of use
// if you lack support for it:
template <typename T>
using ExtractB = typename extract_b<T>::type;
template<typename A>
struct M {
typedef ExtractB<A> B;
// ...
};
traits类的名称不好,但您可以看到,我可以从A<B>
中获得template
参数,并在M<A>
中公开它。
相关文章:
- 如何反转整数参数包
- 关于如何在具有单个参数的变体构造中选择替代方案?
- 模板模板参数方案
- 带有"up-"和"center-vec3"参数的glm::rotate()的有效替代方案?
- 继承是否是将一组模型参数传递给不同类的可行解决方案
- 用于在 Visual Studio 中为整个项目或解决方案定义带有参数的预处理器宏的选项
- 在 C++14 中,是否有一种优雅的解决方案可以在可变参数模板中选择可调用和不可调用的类型
- 从Swift中的通用参数继承的替代方案
- 如何在Xcode 5中使用编辑方案将参数传递给main.cpp
- 使用模板模板参数的替代方案
- 任何解压缩向量以在C++中函数参数的解决方案
- 单例方案,使用不同的参数重载 getInstance
- 具有递归可变参数模板的函数的部分模板专用化的替代方案
- 用于未使用参数参考的单线解决方案
- 采用N个参数并返回N个值的高性能解决方案
- 使用强typedef作为Boost参数库的更轻量级的替代方案
- std::enable_if和模板模板参数显式重载的替代方案
- 将include/library目录和链接器参数传播到解决方案中的所有项目
- OpenGL GLEW的替代品,定义了参数或解决方案
- 函数参数 -> 结构体成员的 void* 和常量 void* 的解决方案