
看了 wiki 上对 decltype 的解释,我的理解就是 decltype 作用就是对表达式的值进行类型推导
然后这个链接( http://www.stroustrup.com/C++11FAQ.html#decltype )给的例子也非常清晰
void f(const vector<int>& a, vector<float>& b) { typedef decltype(a[0]*b[0]) Tmp; for (int i=0; i<b.size(); ++i) { Tmp* p = new Tmp(a[i]*b[i]); // ... } // ... } 但是下面这段代码还是不太能够理解
class Json final { // Implicit constructor: anything with a to_json() function. template <class T, class = decltype(&T::to_json)> Json(const T & t) : Json(t.to_json()) {} ... 代码里注释说,任何一个带有 to_json 成员函数的类的对象,都可以用来初始化这个 Json 类。
template<class T, class = decltype(&T::to_json)>
这个到底应该怎么理解呢?
谢谢
1 htfy96 2015-10-08 20:17:59 +08:00 这是 SFINAE 。要想实例化这个构造函数,即实例化这个函数模板,必须要能推导出 template 列表中的所有 type 。 如果一个类 T 并不具有 T::to_json ,那么推导会失败。然而由于匹配失败不是失败的原理,它会去寻找其它构造函数或放弃 |
3 deetincelle 213 天前 谢谢了。。。 |