template<typename T>:只允许静态数据成员模板

Tey*_*tix 2 c++ templates c++14 template-variables

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

Value_1给出一个错误,说只允许静态数据成员模板。有没有办法保持value_1没有类型?

Rei*_*ica 6

必须知道非静态数据成员的类型。否则是什么sizeof(value)

要存储任意类型的值,您可以使用std::anyboost::any

用:

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);
    }
};
Run Code Online (Sandbox Code Playgroud)