相关疑难解决方法(0)

为什么我的函数超载不是我的模板优先?

根据这个问题的第一个答案:函数模板重载,"非模板化(或"模板化程度较低")重载优于模板".

#include <iostream>
#include <string>
#include <functional>

void f1 (std::string const& str) {
    std::cout << "f1 " << str << std::endl;
}

template <typename Callback, typename... InputArgs>
void call (Callback callback, InputArgs ...args) {
    callback(args...);
}

void call (std::function<void(std::string const&)> callback, const char *str) {
    std::cout << "custom call: ";
    callback(str);
}

int main() {
    auto f2 = [](std::string const& str) -> void {
        std::cout << "f2 " << str << std::endl;
    };

    call(f1, "Hello World!"); …
Run Code Online (Sandbox Code Playgroud)

c++ templates overload-resolution c++11

4
推荐指数
1
解决办法
257
查看次数

什么是lambda函数类型?C++

看我的代码:

#include <iostream>
#include <typeinfo>

int main() {
    auto x = [](int a, int b) -> bool{return a<b;};
    std::cout<<typeid(decltype(x)).name()<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这就是印刷Z4mainEUliiE_.谁能解释一下whay?什么是x的实际类型?

c++ lambda decltype c++11 c++14

4
推荐指数
1
解决办法
276
查看次数

存储 lambda 函数的对象是否有自己的地址?

基于本主题的结果

不捕获任何变量([] 内没有任何内容)的 lambda 可以转换为函数指针

我写了一个像这样的程序

void test1(){}
int main() {
    auto test2 = [](){};
    printf("%p\n%p\n", test1, &test1);
    printf("%p\n%p", test2, &test2);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果是

0x561cac7d91a9

0x561cac7d91a9

0x7ffe9e565397

(零)

https://www.programiz.com/cpp-programming/online-compiler/

那么 test2 存储了一个指向 lambda 函数的函数指针?

我的问题是存储 lambda 数据的对象 test2 没有自己的地址?

我认为这个 test2 应该有自己的地址。

c++ lambda

3
推荐指数
1
解决办法
65
查看次数

如何用函数指针声明lambda(没有auto)?

我可以轻松地声明匿名函数(它们与lambda相同,但没有"context" - [...])auto:

#include <iostream>

using namespace ::std;

void foo(void (*f)(char))
{
    f('r');
}

int main()
{
    void (*anon)(char) = [](char c) -> void { cout << c << endl; };
    foo(anon);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是如何宣布lambda?这是唯一可能的方式吗?(也许使用typedef).我在这里使用::std::function,但我没有在foo参数中提到f的上下文...:

#include <iostream>
#include <functional>

using namespace ::std;

//int foo(auto f, char x) // !only since c++14
int foo(function<int(char)> f, char x)
{
    return f(x+1);
}

int main()
{
    int a = 5, b = 10;

    //void (*lambda)(char) …
Run Code Online (Sandbox Code Playgroud)

c++ lambda pointers anonymous-function auto

2
推荐指数
1
解决办法
499
查看次数

如何存储和调用可变参数函数和值向量?

在Python中,可以存储具有不同数量参数的函数指针,并将参数存储在列表中,然后解压列表并调用该函数,如下所示:

\n
def Func(x1, x2):\n   return x1+x2\nArgList = [1.2, 3.22]\nMyClass.Store(Func)\nMyClass.FuncPtr(*ArgList)\n
Run Code Online (Sandbox Code Playgroud)\n

在c++中是否可以做类似的事情?

\n

例如,将具有可变数量的输入和值的函数存储在 a 中,std::vector并通过该向量调用函数指针?

\n

我不想将参数列表定义为向量。

\n

c++ templates class variadic-templates c++11

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