我想按照以下方式做点什么:
Type type = int; // or type_of(some_other_variable)
double variable = 42.0;
std::cout << (type)variable;
有可能吗?
编辑:我真正想做的是制作一个Qt风格的Variant和VariantMap。我目前的代码是;#include <string>
#include <map>
#include <iostream>
struct Variant
{
bool m_bool;
int m_int;
double m_double;
std::string m_string;
Variant() {};
Variant(bool bBoolean) { m_bool = bBoolean; }
Variant(int iInteger) { m_int = iInteger; }
Variant(double dDouble) { m_double = dDouble; }
Variant(std::string sString) { m_string = sString; }
Variant(const char *_Ptr) { m_string = _Ptr; }
operator bool() { return m_bool; }
operator int() { return m_int; }
operator double() { return m_double; }
operator std::string() { return m_string; }
};
typedef std::map<std::string, Variant> VariantMap;
int main()
{
VariantMap map;
map["bool"] = true;
map["int"] = 42;
map["double"] = 3.14159265358979323846;
map["string"] = "foobar";
std::cout
<< "bool " << static_cast<bool>(map["bool"]) << std::endl
<< "int" << static_cast<int>(map["int"]) << std::endl
<< "double " << static_cast<double>(map["double"]) << std::endl
<< "string "<< static_cast<std::string>(map["string"]) << std::endl
;
system("pause");
return 1;
}
但是,当需要访问时,我不想显式地转换为包含的类型,而是希望在分配时存储类型,并在访问时自动转换为存储的类型。
答案 0 :(得分:3)
using type = int; // or: typedef int type;
std::cout << static_cast<type>(variable); // prefer static_cast to C-style cast
现在,如果你的意思是type
在运行时才会知道(因为它取决于用户输入或其他东西),那么你在C ++中无法提出要求。