相关疑难解决方法(0)

clang错误:非类型模板参数是指没有链接的函数 - bug?

我有一些非常简单的(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通过允许它过于宽松)?


编辑#1:要清楚,这不是这个问题的重复,因为在C++ 11中删除了'不能使用本地类型作为模板参数'限制.但是,仍然不清楚使用本地类型是否涉及链接问题,以及发出此错误时clang是否正确.


编辑#2:已经确定clang对于上面的代码发出错误是正确的(参见@jxh的回答),但它错误地也为下面的代码发出错误(using声明从foo<Bar>()范围移到main()范围):

template<void(*FUNC_PTR)(void)>
struct Func …
Run Code Online (Sandbox Code Playgroud)

c++ gcc templates clang c++11

9
推荐指数
1
解决办法
1765
查看次数

转发模板自动

上下文

(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)
error: no type named 'return_type' in 'callable_trait<void (*)()>'
using return_type = typename callable_trait<decltype(callable)>::return_type;
^~~~~
Run Code Online (Sandbox Code Playgroud)

一个lambda没有帮助......

auto lambda= [](){};
void h(return_type<lambda>);
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>);
                   ^ …
Run Code Online (Sandbox Code Playgroud)

c++ templates type-traits c++17

7
推荐指数
1
解决办法
273
查看次数

包含函数指针的类可以用作非类型模板参数吗?

考虑以下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)

c++ templates language-lawyer non-type c++20

6
推荐指数
1
解决办法
171
查看次数

标签 统计

c++ ×3

templates ×3

c++11 ×1

c++17 ×1

c++20 ×1

clang ×1

gcc ×1

language-lawyer ×1

non-type ×1

type-traits ×1