2
class value {
    template<typename T> T value_1;
    float value_2;

public:
    template<typename T> void Set1(T first) {
        value_2 = (float)0;
        value_1 = first;
    }

    void Set2(float second) {
        value_2 = second;
    }

    float Get2() {
        return this->value_2;
    }

    template<typename T> T Get1() {
        return value_1;
    }
};

Value_1 gives out an error, saying that only static data member templates are allowed. Is there a way to keep value_1 without a type?

max66
  • 65,235
  • 10
  • 71
  • 111
Teytix
  • 85
  • 1
  • 4
  • 10
  • 2
    Think about this: How would you be able to create an object of this class if `T` is not known? It's not possible. One solution is to make the whole class a template. – Some programmer dude Feb 01 '18 at 17:31

1 Answers1

6

The type of a non-static data member must be known. Otherwise, what's sizeof(value)?

To store a value of an arbitrary type, you can use std::any or boost::any.

Use:

class value {
    std::any value_1;
    float value_2;

public:
    template<typename T> void Set1(T first) {
        value_2 = (float)0;
        value_1 = first;
    }

    void Set2(float second) {
        value_2 = second;
    }

    float Get2() {
        return this->value_2;
    }

    template<typename T> T Get1() {
        return std::any_cast<T>(value_1);
    }
};
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455