相关疑难解决方法(0)

使用STL算法的本地类

我一直想知道为什么你不能使用本地定义的类作为STL算法的谓词.

在问题:接近STL算法,lambda,本地类和其他方法,BubbaT提到" 由于C++标准禁止将本地类型用作参数 "

示例代码:

int main() {
   int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   std::vector<int> v( array, array+10 );

   struct even : public std::unary_function<int,bool>
   {
      bool operator()( int x ) { return !( x % 2 ); }
   };
   std::remove_if( v.begin(), v.end(), even() ); // error
}
Run Code Online (Sandbox Code Playgroud)

有谁知道标准中的限制在哪里?禁止当地类型的理由是什么?


编辑:从C++ 11开始,使用本地类型作为模板参数是合法的.

c++ stl stl-algorithm

50
推荐指数
2
解决办法
5645
查看次数

使用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++ ×2

c++17 ×1

lambda ×1

non-type ×1

stl ×1

stl-algorithm ×1

templates ×1