相关疑难解决方法(0)

std :: function vs template

感谢C++ 11,我们收到了std::functionfunctor包装器系列.不幸的是,我一直只听到关于这些新增内容的不好的事情.最受欢迎的是它们非常慢.我对它进行了测试,与模板相比,它们真的很糟糕.

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

template <typename F>
float calc1(F f) { return -1.0f * f(3.3f) + 666.0f; }

float calc2(std::function<float(float)> f) { return -1.0f * f(3.3f) + 666.0f; }

int main() {
    using namespace std::chrono;

    const auto tp1 = system_clock::now();
    for (int i = 0; i < 1e8; ++i) {
        calc1([](float arg){ return arg * 0.5f; });
    }
    const auto tp2 = high_resolution_clock::now();

    const auto d = duration_cast<milliseconds>(tp2 - tp1);  
    std::cout << …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11 std-function

156
推荐指数
7
解决办法
6万
查看次数

是否存在函数指针未涵盖的std :: function的用例,还是仅仅是语法糖?

与函数指针相比​​,std :: function的表示法非常好.但是,除此之外,我找不到一个用指针无法替换的用例.那么它只是函数指针的语法糖吗?

c++ c++-standard-library c++11 std-function

12
推荐指数
2
解决办法
2098
查看次数

C++函数作为Template Argument vs Parameter传递

在C++中,有两种方法可以将函数传递给另一个看似等效的函数.

#include <iostream>

int add1(int i){ return i+1; }
int add2(int i){ return i+2; }

template <int (*T)(int) >
void doTemplate(int i){
    std::cout << "Do Template: " << T(i) << "\n";
}

void doParam(int i, int (*f)(int)){
    std::cout << "Do Param: " << f(i) << "\n";
}

int main(){
    doTemplate<add1>(0);
    doTemplate<add2>(0);

    doParam(0, add1);
    doParam(0, add2);
}
Run Code Online (Sandbox Code Playgroud)

doTemplate接受一个函数作为模板参数,而doParam接受它作为函数指针,它们似乎都给出了相同的结果.

使用每种方法之间的权衡是什么?

c++ templates function

9
推荐指数
2
解决办法
1388
查看次数