【问题标题】:How do I dynamically set a type?如何动态设置类型?
【发布时间】:2016-03-07 12:18:13
【问题描述】:

我一直在尝试编写从文本输入文件读取和初始化图形的代码。

现在,图是一个模板类Graph<K, V>,其中K 是节点键的类型,V 是节点值的类型。

假设我想从这种形式的文本文件中输入一个图表:

char;int    // the types
a;b;c       // the keys
a;b,32;c,5  // edges starting from a
b;c,2       // edges starting from b

如何将类型存储在变量中以初始化图形?

我想做这样的事情:

getline(file, value, ';');
string keyTypeString = value;
getline(file, value);
string valueTypeString = value;

type keyType = ...
type valueType = ...

Graph<keyType, valueType> graph = ...

如何在 C++ 中做到这一点?有没有可能?

【问题讨论】:

  • C++ 是一种静态类型语言,类型是在编译时设置的,不能在运行时更改。所以不,你想做的事情是不可能的,你必须想出另一种方法来解决你的问题。
  • 不,不是。至少不是你想象的那样。模板实例化的类型是静态的,在编译期间在任何文件打开之前就决定了。
  • 你必须使用一个可以存储不同类型的对象。看看 boost::any
  • 如果您的程序除了比较和打印标签之外没有对标签做任何有意义的事情,请始终使用Graph&lt;std::string,std::string&gt;

标签: c++ class templates generics


【解决方案1】:

如果您在编译时知道所有可能 types 然后使用Boost.Variant。文档中有很多例子,但基本上你会得到类似的东西:

using type = boost::variant<char, int>;

std::string input;
std::getline(file, input);

type value;

try {
    value = boost::lexical_cast<int>(input);
} catch(const boost::bad_lexical_cast&) {
    value = input.front(); // char
}

【讨论】:

    【解决方案2】:

    这是不可能的。 C++ 是一种静态类型语言。您应该使用能够存储任何类型的值的特定容器。看看http://www.boost.org/doc/libs/1_60_0/doc/html/any.html

    来自 boost 网站的示例:

    #include <list>
    #include <boost/any.hpp>
    
    using boost::any_cast;
    typedef std::list<boost::any> many;
    
    void append_int(many & values, int value)
    {
        boost::any to_append = value;
        values.push_back(to_append);
    }
    
    void append_string(many & values, const std::string & value)
    {
        values.push_back(value);
    }
    
    void append_char_ptr(many & values, const char * value)
    {
        values.push_back(value);
    }
    
    void append_any(many & values, const boost::any & value)
    {
        values.push_back(value);
    }
    
    void append_nothing(many & values)
    {
        values.push_back(boost::any());
    }
    

    所以在你的情况下,你可以有一个Graph&lt;keyType, boost::any&gt; 图表。您应该将存储在图表中的类型存储在某个地方。但是当你必须处理具体类型时,你会使用switch case 语句

    【讨论】:

      【解决方案3】:

      没有

      在 C++ 中这是不可能的。模板是一个编译时间结构。在其他语言中,相同的问题集通过他们称为“泛型”的不同结构来解决,在运行时可以解决,但对于 C++ 中的模板,情况并非如此。

      【讨论】:

        猜你喜欢
        • 2018-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-05
        • 2011-02-28
        • 2021-07-14
        • 2019-12-11
        相关资源
        最近更新 更多