c++ - 可以使用自动占位符来推断非类型模板参数中的函数结果吗?

标签 c++ templates language-lawyer c++17

考虑一个简单的例子:

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/

相关文章:

c++ - 在库的公共(public)接口(interface)中使用 boost::shared_ptr

c++ - C++ 中的流畅接口(interface)和继承

c++ - C++ 中的模板函数?也许不是正确的术语

c++ - 关于简历分解的困惑

c++ - 是否为包含相同值的范围定义了 std::nth_element?

c++ - 在ubuntu中使用Opencv编译警告

c - 通过定义明确的 offsetof 访问成员吗?

c++ - 下标时是否必须使用 constexpr 数组?

php - 为什么我在 Laravel View 中得到 "Undefined variable"?

c++ - 使用 C++ 模板作为 objective-c 方法的参数