考虑一个简单的例子:
template <auto(*X)()>
struct Foo {
decltype(X()) x;
};
int bar();
int main() {
static_cast<void>(Foo<bar>{});
}
两者都是[gcc]和 [clang]似乎接受代码。代码真的符合 c++17 标准吗?如果是这样,是否有其他规则导致以下代码格式错误?
template <class T, auto(*X)(T)>
struct Foo {
decltype(X(0)) x;
};
int bar(int);
int main() {
static_cast<void>(Foo<int, bar>{});
}
这个只做[gcc]不开心。
错误信息:
prog.cc: In function 'int main()':
prog.cc:9:35: error: unable to deduce 'auto (*)(T)' from 'bar'
static_cast<void>(Foo<int, bar>{});
^
prog.cc:9:35: note: mismatched types 'T' and 'int'
最佳答案
是的,可以使用auto
inside a compound type ( [temp.param]/4.6 , [dcl.type.auto.deduct] )。我相信 gcc 在你的第二个例子中是错误的:你明确指定的 T
of int
在执行推导之前被替换([temp.deduct]/2.3,/5,和/6,由 [dcl.type.auto.deduct]/2.3 和/4 引用。
关于c++ - 可以使用自动占位符来推断非类型模板参数中的函数结果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48481057/