Why can I not inline a function in my class? [duplicate]

帅比萌擦擦* 提交于 2021-01-07 21:01:50

问题


I am learning c++ by writing commons data structures and I have a compiler warning that my inlined add method is not defined.

src/vector.h:10:14: warning: inline function 'Vector::add' is not defined
      [-Wundefined-inline]
        inline void add(const float val);

What am I doing wrong? As far as I can tell the methods match up. However if I remove the inline method, it works fine but the first invocation of add takes 11380us but the 2nd and 3rd are around 3667us -nearly 4x penalty cost.

src/vector.h

//#include <cstddef>

class Vector {
public:
    explicit Vector(const int n);
    explicit Vector(const int n, const float val);
    float& operator[](const int i);
    inline int const length();
    inline void fill(const float val);
    inline void add(const float val);
    inline float sum();
private:
    float* arr;
    int len;
};

src.vector.cpp

#include "vector.h"
#include <iostream>
#include <algorithm>
#include "yepCore.h"
#include "yepMath.h"
#include "yepLibrary.h"
#include <cstdlib>

using namespace std;

inline void Vector::add(const float val)
{
    chrono::steady_clock::time_point start = chrono::steady_clock::now();   
    for (int i = 0; i < len; ++i) {
        arr[i] += val;
    }
    chrono::steady_clock::time_point end = chrono::steady_clock::now();
    cout << "yepp add took " << chrono::duration_cast<chrono::microseconds>(end - start).count()
              << "us.\n";
}

/**
template <>
void Vector<float>::add(const float val)
{
    chrono::steady_clock::time_point start = chrono::steady_clock::now();   
    yepCore_Add_V32fS32f_V32f(arr, val, arr, len);
    chrono::steady_clock::time_point end = chrono::steady_clock::now();
    cout << "yepp add took " << chrono::duration_cast<chrono::microseconds>(end - start).count()
              << "us.\n";

}
...

回答1:


Inline functions must be defined in the header. If they are not defined in the header file, then the function cannot be inlined, because callers won't have the definition.



来源:https://stackoverflow.com/questions/26105525/why-can-i-not-inline-a-function-in-my-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!