我有一些非常简单的(C++ 11)代码,最新的clang(版本3.4 trunk 187493)无法编译,但GCC编译得很好.
代码(下面)foo使用函数本地类型 实例化函数模板,Bar然后尝试将其地址用作类模板的非类型模板参数Func:
template<void(*FUNC_PTR)(void)>
struct Func {};
template<typename T> extern inline
void foo() {
using Foo = Func<foo<T>>;
}
int main() {
struct Bar {}; // function-local type
foo<Bar>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
clang发出以下错误:
错误:非类型模板参数是指没有链接的函数'foo'
但是,如果我将类型移动Bar到全局范围(通过将其从函数中取出),则clang可以很好地编译它,证明问题在于函数本地类型.
那么clang是否正确发出此错误,或者标准是否不支持这种情况(在这种情况下,GCC通过允许它过于宽松)?
using声明从foo<Bar>()范围移到main()范围):
template<void(*FUNC_PTR)(void)>
struct Func …Run Code Online (Sandbox Code Playgroud) (1)可以使用以下特征提取可调用的返回类型和参数类型:
#include <tuple>
template<class T>
struct callable_trait
{};
template<class R, class... Args>
struct callable_trait<R(Args...)>
{
using return_type = R;
using argument_types = std::tuple<Args...>;
};
Run Code Online (Sandbox Code Playgroud)
(2)从C++ 17开始,可以使用以下命令定义模板template<auto>:
如果声明了模板参数
auto,则从相应的参数中推导出其类型.
(3)然后我应该能够提供一些语法糖:
template<auto callable>
using return_type = typename callable_trait<decltype(callable)>::return_type;
Run Code Online (Sandbox Code Playgroud)
......但是效果不好......
void f();
void g(return_type<f>);
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)error: no type named 'return_type' in 'callable_trait<void (*)()>' using return_type = typename callable_trait<decltype(callable)>::return_type; ^~~~~
一个lambda没有帮助......
auto lambda= [](){};
void h(return_type<lambda>);
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)error: a non-type template parameter cannot have type '(lambda at <source>:19:14)' void h(return_type<lambda>); ^ …
考虑以下S包含函数指针的类,以及使用 lambda 初始化的该类的constexpr对象s:
struct S
{
void (*f) ();
};
constexpr S s { []{} };
Run Code Online (Sandbox Code Playgroud)
现在,如果我X使用 type 的非类型模板参数编写模板S,并s像这样实例化它:
template<S> struct X {};
using x = X<s>;
Run Code Online (Sandbox Code Playgroud)
clang 编译代码,但 gcc 抱怨:
error: '<lambda()>::_FUN' is not a valid template argument of type 'void (*)()' because '<lambda()>::_FUN' is not a variable
using x = X<s>;
^
Run Code Online (Sandbox Code Playgroud)
这是程序。
代码对我来说似乎很好,我不确定错误消息指的是什么。那么这个代码有效吗?
请注意,如果X有一个引用类型为 to 的非类型模板参数,则两个编译器都接受代码S,如下所示:
template<S const &> …Run Code Online (Sandbox Code Playgroud)