我对C++11的特性比较陌生。我有关于自动功能的问题,以及它是如何类型推导函数器的。考虑下面的代码片段:
bool test1(double a, double b) {
return (a<b);
}
bool test2(double a, double b) {
return (a>b);
}
struct Test1 {
bool operator()(double a, double b) {
return (a<b);
}
};
struct Test2 {
bool operator()(double a, double b){
return (a>b);
}
};
int main() {
const bool ascending = false;
auto comparator = ascending? test1:test2; // works fine
auto comparator2 = ascending? Test1():Test2(); // compiler error: imcompatible types
std::function<bool(double, double)> comparator3 = ascending? Test1():Test2(); // compiler error: imcompatible types;
}虽然auto (和std:: function )对于函数工作得很好,但是对于function对象它却失败了(type-deduction)。为什么会这样呢?我在这里遗漏了一些基本的w.r.t类型-演绎。
(我正在使用Visual Studio 2012)
发布于 2013-03-27 05:10:05
根据关于条件(?)运算符的C++11标准的第5.16/3段:
...如果第二和第三操作数具有不同的类型并且或者具有(可能是cv限定的)类类型,或者如果两个操作数都是除了cv限定之外的相同值类别和相同类型的GL值,则尝试将这些操作数中的每一个转换为另一个的类型。如果两个都可以转换,或者其中一个可以转换但转换不明确,则程序是格式错误的。..。
在您的示例中,Test1和Test2都不能转换为另一种类型。这就是为什么编译器会抱怨“类型不兼容”。
如果不是这样,comparator2和comparator3的类型将在运行时根据ascending的值确定。然而,C++是一种静态类型的语言,这意味着所有对象的类型必须在编译时中确定。
如果需要执行比较器的运行时选择并将结果保存在一个变量中,请考虑首先将这两个对象分配给可以封装它们的同一类型的functor,然后执行选择:
std::function<bool(double, double)> c1 = Test1();
std::function<bool(double, double)> c2 = Test2();
auto c = (ascending) ? c1 : c2;发布于 2013-03-27 05:08:36
问题是条件运算符?:的两个选项必须可转换为单个公共类型。在这种情况下,Test1和Test2是不相关的,并且不可能像那样使用运算符。
然而,这是合法的:
int main() {
const bool ascending = false;
std::function<bool(double, double)> t1 = Test1();
std::function<bool(double, double)> t2 = Test2();
auto comparator4 = ascending? t1: t2;
}发布于 2013-03-27 05:08:50
test1和test2都属于bool(double, double)类型,因此无论采用哪个分支,条件表达式的类型都是相同的。Test1()的类型是Test1,Test2()的类型是Test2。因此,表达式没有公共类型。这两种类型都可以使用该类的构造函数模板来构造std::function<bool(double, double)>对象,但这种类型的强制转换不会自动为表达式执行:您必须手动强制转换:
auto comparator3 = ascending ? std::function<bool(double, double)>(Test1())
: std::function<bool(double, double)>(Test2());https://stackoverflow.com/questions/15647350
复制相似问题