【发布时间】:2016-11-14 12:13:51
【问题描述】:
考虑以下几点:
template<typename Der>
struct Base {
// NOTE: if I replace the decltype(...) below with auto, code compiles
decltype(&Der::operator()) getCallOperator() const {
return &Der::operator();
}
};
struct Foo : Base<Foo> {
double operator()(int, int) const {
return 0.0;
}
};
int main() {
Foo f;
auto callOp = f.getCallOperator();
}
我想在 CRTP 基类中创建一个成员函数,其返回类型取决于派生类中 operator() 的签名。但是decltype(&Der::operator()) 编译失败; Foo 中的 operator() 成员函数不可见。我假设这是因为基类模板是在 Foo 完全定义之前实例化的。
令人惊讶的是,如果我将 auto 放置为它编译的返回类型。我假设auto 会使编译器从函数体中推断出返回类型并失败——因为函数体使用了未完全定义的Foo 类型。
MSVC 2015.3 和 Clang 3.8 的此行为相同
为什么代码开始使用auto? auto 类型推断是否以某种方式“延迟”实例化?或者使用与手写返回类型表达式不同的上下文?
【问题讨论】:
-
好问题。赞成。
-
同一个问题,但问答的角度略有不同。这里我们有“自动演绎的不同之处”,链接的问题及其答案更多的是关于“我怎样才能使手写表达起作用”。虽然它可能仍然符合重复的条件......
标签: c++ c++14 crtp return-type-deduction