C++ 什么是非导出上下文?
最近,我无意中读到了“”一词,答案可以总结为“这是一个非派生的上下文” 具体地说,第一个引用的是这样一个东西,然后重定向到“细节”标准,而第二个引用的是标准,至少可以说是晦涩难懂的 有人能向像我这样的凡人解释什么是非导出上下文,何时发生,为什么发生?演绎指的是从给定参数确定模板参数类型的过程。它适用于函数模板、C++ 什么是非导出上下文?,c++,templates,template-argument-deduction,C++,Templates,Template Argument Deduction,最近,我无意中读到了“”一词,答案可以总结为“这是一个非派生的上下文” 具体地说,第一个引用的是这样一个东西,然后重定向到“细节”标准,而第二个引用的是标准,至少可以说是晦涩难懂的 有人能向像我这样的凡人解释什么是非导出上下文,何时发生,为什么发生?演绎指的是从给定参数确定模板参数类型的过程。它适用于函数模板、auto,以及一些其他情况(例如部分专用化)。例如,考虑: template <typename T> void f(std::vector<T>); 在此函数模
auto
,以及一些其他情况(例如部分专用化)。例如,考虑:
template <typename T> void f(std::vector<T>);
在此函数模板中,函数参数列表中的T
处于非推断上下文中。因此,你不能说g(x)
,也不能推断T
。原因是任意类型和成员之间没有“向后对应关系”Foo::type
。例如,您可以有专门化:
template <> struct Foo<int> { using type = double; };
template <> struct Foo<char> { using type = double; };
template <> struct Foo<float> { using type = bool; };
template <> struct Foo<long> { int type = 10; };
template <> struct Foo<unsigned> { };
如果调用二进制函数(t,u)
,则演绎可能不明确,因此会失败。但只推导一个参数而不推导另一个参数是合理的,因此允许隐式转换。现在需要一个明确的非推断上下文,例如:
template <typename T>
struct type_identity {
using type = T;
};
template <typename T>
bool binary_function(Foo<T> lhs, typename type_identity<Foo<T>>::type rhs)
{
return binary_function(lhs, rhs);
}
模板
结构类型标识{
使用类型=T;
};
模板
bool二进制函数(Foo-lhs,typename-type\u-identity::type-rhs)
{
返回二进制函数(lhs、rhs);
}
(您可能遇到过类似于
std::min(1U,2L)
的演绎问题)相关:因此您正在引用标准描述的第二种情况(“一种模板id类型,其中一个或多个模板参数是引用模板参数的表达式”),对吗?如果是这样的话,你能举一个第一个例子(“使用限定id指定的类型的嵌套名称说明符”)吗?事实上,现在我仔细阅读了它,我认为它正好相反。@Jeffrey:可能类似于模板结构条;模板空隙(条形)代码>?要点是:类型T
和模板类Foo
之间存在一对一的对应关系,因此可以从后者推断前者。但是类型T
和任意成员Foo::X
之间没有对应关系。我觉得您也可以回答。
template <typename T> bool binary_function(Foo<T> lhs, Foo<T> rhs);
template <typename T>
struct type_identity {
using type = T;
};
template <typename T>
bool binary_function(Foo<T> lhs, typename type_identity<Foo<T>>::type rhs)
{
return binary_function(lhs, rhs);
}