c++ - 模板函数内的全局值不改变 [c++]

标签 c++ function templates variables global

我需要一个项目的帮助。基本上我需要测量一些排序算法的时钟滴答声。由于它们都使用比较,有时还使用交换函数,因此我将它们设计为接受这些作为回调函数。

测量我写的时钟滴答声:

static clock_t t1, total;

template<typename T>
bool less_default(T & left, T & right){
    t1 = clock(); 
    bool v = left < right; 
    t1 = clock() - t1;
    total += t1
    return v;
}

当我实际运行算法时,total 或 t1 都没有反射(reflect)出任何变化。好像引用它们的代码行从未写过。

没有任何作用。函数调用时甚至没有一个简单整数的增量。

是不是静态全局变量不能在模板函数内部改变?

我不明白我在这里做错了什么。

最佳答案

nothing works. Not even an increment of a simple integer on function call.

我怀疑以下内容出现在header 文件中:

static clock_t t1, total;

如果是这种情况,每个翻译单元将获得两个变量的独立实例(感谢 static)。

要修复,请将 header 中的 static 更改为 extern,并将以下内容添加到 .cpp 文件中:

clock_t t1, total;

EDIT 示例如下:

根据 OP 的要求,这是一个简短示例,它使用模板比较器和此答案中的配方来声明和管理运行时钟总数。

ma​​in.h

#ifndef PROJMAIN_DEFINED
#define PROJMAIN_DEFINED

extern clock_t total;

template<typename T>
bool less_default(const T& left, const T& right)
{
    clock_t t1 = clock();
    bool res = (left < right);
    total += (clock() - t1);
    return res;
};

#endif

main.cpp

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include "main.h"
using namespace std;

clock_t total = 0;

int main()
{
    static const size_t N = 2048;
    vector<int> values;
    values.reserve(N);
    std::srand((unsigned)time(0));

    cout << "Generating..." << endl;
    generate_n(back_inserter(values), N, [](){ static int i=0; return ++i;});

    for (int i=0;i<5;++i)
    {
        random_shuffle(values.begin(), values.end());
        cout << "Sorting ..." << endl;
        total = 0;
        std::sort(values.begin(), values.end(), less_default<int>);
        cout << "Finished! : Total = " << total << endl;
    }
    return EXIT_SUCCESS;
}

输出

Generating...
Sorting ...
Finished! : Total = 13725
Sorting ...
Finished! : Total = 13393
Sorting ...
Finished! : Total = 15400
Sorting ...
Finished! : Total = 13830
Sorting ...
Finished! : Total = 15789

关于c++ - 模板函数内的全局值不改变 [c++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15403325/

相关文章:

c++ - 使用数组的模板专门化,std::is_array

c++ - 双链表查找删除

c++ - 组合继承自的类的对象?

c++ - _InterlockedCompareExchange 文档中 "The sign is ignored"的含义

javascript - 如何创建 JavaScript 延迟函数

c++ - 如何同时提供默认模板参数和模板函数实参默认值?

c++ - 以下程序中创建的用于 map 初始化的临时变量在哪里

c - ZEROMQ 编译器错误中的 zhelpers.h

java - 检查所有函数中的所有函数参数

c++ - 在 Windows 中编译 Faster RNNLM 的问题