use*_*404 3 c++ variables variable-types
我有一个c ++类,如下所示:
class some_class {
protected:
decide_later some_variable;
public:
void some_random_function();
};
void some_class::some_random_function() {
decide_later another_variable;
}
Run Code Online (Sandbox Code Playgroud)
问题是,在创建类的实例之前,我不知道some_variable将是什么变量类型.我想做的是如下:
some_class class_instance(std::string);
Run Code Online (Sandbox Code Playgroud)
这会将decision_later设置为使用std :: string(或int,或double,或者告诉它使用的任何东西).另外,如果我可以在其他作为类成员的函数中使用decision_later作为变量类型,那将是很好的.例如,在函数some_random_function()中.
我曾尝试使用boost :: any来做到这一点,但它似乎只适用于数字类型.此外,我认为如果能够实际设置实际的变量类型会更有效率.
这可能吗?
您正在寻找模板.声明你的班级:
template <typename T> class some_class {
protected:
T some_variable;
public:
void some_random_function() {
T another_variable;
}
};
Run Code Online (Sandbox Code Playgroud)
并实例化它:
some_class<std::string> class_instance();
Run Code Online (Sandbox Code Playgroud)