相关疑难解决方法(0)

将捕获lambda作为函数指针传递

是否可以将lambda函数作为函数指针传递?如果是这样,我必须做错了,因为我收到编译错误.

请考虑以下示例

using DecisionFn = bool(*)();

class Decide
{
public:
    Decide(DecisionFn dec) : _dec{dec} {}
private:
    DecisionFn _dec;
};

int main()
{
    int x = 5;
    Decide greaterThanThree{ [x](){ return x > 3; } };
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,我得到以下编译错误:

In function 'int main()':
17:31: error: the value of 'x' is not usable in a constant expression
16:9:  note: 'int x' is not const
17:53: error: no matching function for call to 'Decide::Decide(<brace-enclosed initializer list>)'
17:53: note: candidates are: …
Run Code Online (Sandbox Code Playgroud)

c++ lambda function-pointers c++11

186
推荐指数
4
解决办法
12万
查看次数

什么是C++中的类型擦除?

所以我正在读这篇关于类型擦除的文章.但该文章中的代码似乎部分不正确,例如:

template <typename T>
class AnimalWrapper : public MyAnimal
{
    const T &m_animal;

public:
    AnimalWrapper(const T &animal)
        : m_animal(animal)
    { }

    const char *see() const { return m_animal.see(); }
    const char *say() const { return m_animal.say(); }
};
Run Code Online (Sandbox Code Playgroud)

其次是

void pullTheString()
{
    MyAnimal *animals[] = 
    {
        new AnimalWrapper(Cow()), /* oO , isn't template argument missing? */
        ....
    };
}
Run Code Online (Sandbox Code Playgroud)

这些错误使我不鼓励在文章中进一步阅读.

无论如何; 有没有人可以用简单的例子教C++中哪种类型的擦除?

我想了解它是如何std::function工作的,但无法理解它.

c++ type-erasure

11
推荐指数
1
解决办法
1794
查看次数

标签 统计

c++ ×2

c++11 ×1

function-pointers ×1

lambda ×1

type-erasure ×1