相关疑难解决方法(0)

使用lambda作为非类型模板参数时为什么gcc失败?

下面的代码片段与Clang 4.0没有错误编译,但GCC 7.0会产生错误(注意使用-std = c ++ 1z标志).

using FuncT = int (*)(double);

template <FuncT FUNC>
int temp_foo(double a)
{
    return FUNC(a);
}

int foo(double a)
{
    return 42;
}

void func()
{
    auto lambda = [](double a) { return 5; };

    struct MyStruct
    {
        static int foo(double a) { return 42; }
    };

    temp_foo<foo>(3);
    temp_foo<static_cast<FuncT>(lambda)>(3);
    temp_foo<MyStruct::foo>(3);
}
Run Code Online (Sandbox Code Playgroud)

具体来说,GCC抱怨lambda和嵌套类的方法都没有链接,所以它们不能用作非类型模板参数.

至少对于lambda案例,我认为Clang是正确的(并且GCC是错误的)因为(引用cppreference,转换运算符):

此转换函数返回的值是指向具有C++语言链接的函数的指针,该函数在调用时具有与直接调用闭包对象的函数调用操作符相同的效果.

海湾合作委员会是否行为不端?

c++ lambda templates non-type c++17

15
推荐指数
1
解决办法
817
查看次数

标签 统计

c++ ×1

c++17 ×1

lambda ×1

non-type ×1

templates ×1