相关疑难解决方法(0)

删除decltype中的引用(返回T而不是T&,其中T&是decltype)

(如果您是C++ 11专业版,请跳到粗体段.)

假设我想编写一个模板方法,该方法调用并返回传递对象的结果,该对象的类型是模板参数:

template<ReturnType, T>
ReturnType doSomething(const T & foo) {
    return foo.bar(); // EDIT: Might also be an expression introducing a temp val
}
Run Code Online (Sandbox Code Playgroud)

所以T必须有一个方法ReturnType T::bar() const才能在这样的调用中使用:

struct MyClass {
    ...
    int bar() const;
    ...
};
...
MyClass object;
int x = doSomething<int, MyClass>(object);
Run Code Online (Sandbox Code Playgroud)

MyClass感谢类型扣除,我们无需写信,调用成为:

int x = doSomething<int>(object);
Run Code Online (Sandbox Code Playgroud)

但是省略<int>也会导致编译错误,因为该方法不需要返回int以便x以后分配(char例如,它可以返回).

在C++ 0X/11,我们有autodecltype,使我们可以用它来推断模板方法的返回类型:

template<T>
auto doSomething(const T & foo) -> decltype(foo.bar()) {
    return foo.bar(); // …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11 type-deduction

46
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

c++11 ×1

templates ×1

type-deduction ×1