0

I am just learning templates in C++ and I came across the idea of using static variables in templates. I created a simple class containing a three dimensional vector. I decided to keep the 'unit caps'(i, j and k) as static so to make it a class property instead of it being an object property:

#include <iostream>

using namespace std;

template <class T = int>
class vector
{
    int *arr;
    static string caps;

public:
    vector() {}

    vector(int arr[]) : arr(arr) {}

    void setVector(int arr[])
    {
        this->arr = arr;
    }

    void displayVector()
    {
        cout << "The vector is : " << arr[0] << caps[0] << " + " << arr[1] << caps[1] << " + " << arr[2] << caps[2] << endl;
    }
};

string vector::caps = "ijk";

And it's throwing an error enter image description here

Then I tried something:


template <class T>
string vector::caps = "ijk";

Still giving error.

  • 2
    Stop `using namespace std;` – StoryTeller - Unslander Monica Apr 20 '23 at 08:59
  • The reason why stop using?? Because you just say stop but dont give a reason why. – laraCoder Apr 20 '23 at 09:00
  • @laraCoder - When sage advice is questioned as some challenge to authority, it becomes more worthwhile to let the novice figure it out the hard way. – StoryTeller - Unslander Monica Apr 20 '23 at 09:03
  • @laraCoder Because `using namespace std;` introduces all names from the std namespace into the current namespace. This potentially leads to conflicts between names defined the std namespace and the current namespace. These conflicts do not necessarily cause compiler errors, just code that does not run correctly. These problems can appear without any warning when new code is written (or even when the standard library changes with a new version of C++). – john Apr 20 '23 at 09:08
  • 1
    You already have an answer to your question, but note that if you change the line to `static constexpr std::string_view caps = "ijk";` you avoid the problem alltogether. – cptFracassa Apr 20 '23 at 09:11
  • 3
    [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). In particular you can never be sure what headers other headers include, hence you now have two `vector` in scope. namespaces are there for a reason, exactly to avoid such name clashes and you add a single line that says: "I prefer confusion" – 463035818_is_not_an_ai Apr 20 '23 at 09:19
  • 2
    and this is not just hypothetical. Suppose you `#include "foo.h"` and that header internally uses `std::vector`, then its just a tiny step to make code that looks ok do the wrong thing. – 463035818_is_not_an_ai Apr 20 '23 at 09:22

0 Answers0