c++ - 模板模板类中非类型参数的类型在 C++14 中不可推导,但在 C++17 中可推导
问题描述
标题有点令人困惑,但我的意思是这个具体案例:
template<class>
struct get_type_of_nontype;
template<class T, T Value, template<T> class Template>
struct get_type_of_nontype<Template<Value>> {
using type = T;
};
所以我可以这样使用它:
#include <type_traits>
template<int I>
class int_non_type {};
static_assert(
std::is_same<typename get_type_of_nontype<int_non_type<0>>::type, int>::value,
"T is deduced to be `int` as `template<T> class Template` is `template<int> class int_non_type`"
);
这在 C++17 中运行良好。在 C++14 中,我收到以下错误:
海湾合作委员会 8:
<source>:5:8: error: template parameters not deducible in partial specialization:
struct get_type_of_nontype<Template<Value>> {
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:5:8: note: 'T'
叮当声7:
<source>:5:8: error: class template partial specialization contains a template parameter that cannot be deduced; this partial specialization will never be used [-Wunusable-partial-specialization]
struct get_type_of_nontype<Template<Value>> {
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:4:16: note: non-deducible template parameter 'T'
template<class T, T Value, template<T> class Template>
^
然后他们都抱怨struct get_type_of_nontype<int_non_type<0>>
不完整,所以typename get_type_of_non_type<int_non_type<0>>::type
无法编译。
为什么在 C++14 和 C++17 之间会有这样的不同?这只是一个编译器错误吗?如果没有,有没有办法在 C++14 中做到这一点?
解决方案
[temp.deduct.type] 第 13 和 14 段中的标准措辞已更改。所以是的,您的示例在 C++14 中无效,但由于新的语言功能,在 C++17 中是允许的。
C++14:
不能从非类型模板参数的类型推导出模板类型参数。
[示例:
template<class T, T i> void f(double a[10][i]); int v[10][20]; f(v); // error: argument for template-parameter T cannot be deduced
--结束示例]
C++17:
P
当从表达式推导出与以依赖类型声明的非类型模板形参对应的实参的值时,从值的类型推导出类型为的模板形参P
。[示例:template<long n> struct A { }; template<typename T> struct C; template<typename T, T n> struct C<A<n>> { using Q = T; }; using R = long; using R = C<A<2>>::Q; // OK; T was deduced to long from the // template argument value in the type A<2>
--end example ]类型
N
中的类型T[N]
是std::size_t
。[示例:template<typename T> struct S; template<typename T, T n> struct S<int[n]> { using Q = T; }; using V = decltype(sizeof 0); using V = S<int[42]>::Q; // OK; T was deduced to std::size_t from the type int[42]
--结束示例]
[示例:
template<class T, T i> void f(int (&a)[i]); int v[10]; void g() { f(v); // OK: T is std::size_t }
--结束示例]
这似乎与另一个 C++17 模板更改有关:C++17 是第一个允许在非类型模板参数中使用占位符类型的版本,例如在template <auto Value>
or中template <auto* Ptr>
。我希望编译器实现需要一些类似的逻辑来支持这两种语言功能。
推荐阅读
- jquery - 如何检查不被jquery隐藏的复选框
- javascript - 以角度将文本转换为html格式
- css - CSS块布局 - 偶数/奇数?
- ethereum - 以太坊:从 Restful API 调用智能合约函数
- javascript - 对数组中不同类型的变量进行排序
- node.js - “awsmobile init”不适用于网络反应
- angular - DatePicker Angular 材质,Angular 5
- swift - 如何使关联值相等的 Swift 枚举
- laravel - Laravel:无法打开流:成功_身份验证错误
- javascript - VS2017中的javascript验证在脚本以外的其他文件夹中