samedi 25 avril 2020

Error with template specialization that relates to static members [duplicate]

When I run the following piece of code,

 #include <iostream>
using namespace std;
enum class Fruit { apple, orange, pear };

template <typename T> struct Traits;

template <>
struct Traits<Fruit> {
    string name(int index) {
        switch (index) {
        case 0:return "apple";
        case 1: return "orange";
        case 2: return "pear";
        }
        return "unknown";
    }
};

int main()
{
    int t = 0; std::cin >> t;

    for (int i = 0; i != t; ++i) {
        int index1; std::cin >> index1;
        int index2; std::cin >> index2;
        cout << Traits<Fruit>::name(index2) << "\n";
    }
}

the error that I get is

Solution.cpp: In function ‘int main()’:
Solution.cpp:122:43: error: cannot call member function ‘std::__cxx11::string Traits<Color>::name(int)’ without object
         cout << Traits<Color>::name(index1) << " ";

which suggests that I don't have an object of the struct before calling a method of the struct. But if I add the keyword static in line 9, so that it becomes static string name(int index){, the code runs properly. Can someone help on what's causing this.

Aucun commentaire:

Enregistrer un commentaire