Skip Navigation

User banner
C++

Members
0
Posts
52
Created
3 yr. ago

The center for all discussion and news regarding C++.

Rules

  • Respect instance rules.
  • Don't be a jerk.
  • Please keep all posts related to C++.

🌉 bridged from !cpp@programming.dev by Tidepool

Learning how templates and operator() work!

#include template <typename T, const int length=5> class vector { public: T v[length]; vector operator +(const vector &obj) { vector tmp; for(int i = 0; i < length; i++) tmp.v[i] = v[i] + obj.v[i]; return tmp; /* This method below only works if length is a fixed size return {v[0] + obj.v[0], v[1] + obj.v[1], v[2] + obj.v[2], v[3] + obj.v[3], v[4] + obj.v[4]};*/ } }; int main() { vector a={1,2,3,4,5}; vector b={1,2,3,4,5};

 
auto c = a + b;

std::cout << "(int) ";
for(int i = 0; i < 5; i++)
    std::cout << c.v[i] << " ";
std::cout << std::endl;

}

Inlining Library functions

So I have the following problem. I am currently writing some Libraries in C++ as a way to get started with the language. In my library I want to use the inline keyword for a function to reduce the overhead caused by lots of function calls. The problem I have is, that it seems like it is not possible to inline functions, if I dont define them in my libraries header file. So I got three files, that I am working with. My library (lib.cpp), its header file (lib.h) and my main code (main.cpp). My testing code for my library looks like this (this is just example code that has the same structure, but with different functionality): main.cpp

 
#include <iostream>
#include "lib.h"
using namespace std;

int main(){
  int count = 5;
  float sum = get_sum(count);
  cout << "Sum of 0-" << count << ": " << sum << endl;


  int num = get_num(6);
  cout << "Got num: " << num << endl;
  return 0;
  return 0;
}

And my library looks like this: lib.cpp

 
#include "lib.h"
inline int get_num(int num){
  return num;
}

int get_sum (int count){
  int sum = 0;
  for(int i = 0; i < count; i++){
    sum = sum + get_num(i);
  }
  return sum;
}

Naturally I created my header file like this: lib.h

 
#ifndef LIB_H
#define LIB_H
inline int get_num(int num);
int get_sum (int count);
#endif 

The problem with this is, that this code will throw an compile error that theres no definition for get_num in main.cpp. This can be fixed by simply moving the entire function with its body into the header file. The problem I have with doing it like this is, that this causes my inline function to not show up inside my lib.cpp file and gets hidden away in the header file. Is there a way that I can define my inline functions in my libraries source code, and expose it as a public function through my header file?