我可以使用模板别名作为模板模板参数吗?
我可以使用模板别名作为模板模板参数吗?
template <template <typename...> class> struct foo {};
template <typename T> using simple_ptr = std::unique_ptr<T>;
foo<std::unique_ptr> a; // this doesn't work, std::unique_ptr has two parameters
foo<simple_ptr> b; // does this work?
Can I use template aliases as template template parameters?
template <template <typename...> class> struct foo {};
template <typename T> using simple_ptr = std::unique_ptr<T>;
foo<std::unique_ptr> a; // this doesn't work, std::unique_ptr has two parameters
foo<simple_ptr> b; // does this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这显然是允许的。根据我能找到的即将发布的标准的最新草案,指出
不过,别名模板目前似乎很少受支持,因此您可能有使其与大多数编译器一起工作时遇到一些麻烦。
Yes, it is apparently allowed. According to the latest draft of the upcoming standard I could find, it is stated that
However, alias templates seems very seldomly supported at the moment, so you might have some trouble making it work with most compilers.
阅读原始问题的人可能正在编写使用模板模板参数作为元函数的结构,如下面的清单所示。
add_1
和add_2
都是元函数,让我们add_1
- style 元函数(c++03 支持)add_2
作为模板别名样式 元函数(需要 c++11)的示例二进制操作
struct 可以与模板别名样式 或嵌套 typedef-style 元函数一起使用,但不能同时使用两者。在这个答案中,我展示了如何重写此类 TMP 代码以避免此问题。假设您希望将模板模板参数
Function
应用于值Ts...
的参数包。要应用元函数,您需要或
拥有另一个通用元函数来检测传递的元函数类型并相应地应用它会很有用。
下面实现的 is_alias_metafunction 函数是此类工具的构建块:
现在,我们可以编写一个应用模板模板参数
Function 的元函数
到参数包apply
Ts...
,无论Function
是模板别名还是模板结构。我们现在可以按如下方式使用
apply
元函数:它将抽象出“旧版”元函数和现代 (c++11) 元函数之间的差异。
People who read the original question may be writing structs that use template template parameters as meta functions, as demonstrated in the listing below.
add_1
andadd_2
are both meta-functions, let's distinguishadd_1
as an example of nested typedef-style metafunction (which c++03 supported)add_2
as an example of template alias-style metafunction (which requires c++11)The
binary_op
struct can work either with template alias-style or nested typedef-style metafunctions, but not both. In this answer, I show how such TMP code can be rewritten to avoid this problem.Suppose that you wish to apply a template template parameter
Function
to a parameter pack of valuesTs...
. To apply the metafunction, you need eitheror
It would be useful to have another generic metafunction that detects the kind of metafunction that was passed, and applys it accordingly.
The
is_alias_metafunction
function, which is implemented below, is a building block for such a facility:Now, we can write a metafunction
apply
that applies a template template parameterFunction
to the parameter packTs...
, regardless of whetherFunction
is a template alias or a template struct.We can now use the
apply
metafunction as follows:and it will abstract away the difference between 'legacy' metafunctions and modern (c++11) metafunctions.