从boost :: program_options值中键入un-erasure

时间:2015-11-20 17:21:01

标签: c++ templates boost-program-options boost-any

我试图用boost::program_options改造我的程序。除此之外,我还编写了一个我无法编译的函数。这是一个最小的.cpp文件,它无法编译:

#include <boost/program_options.hpp>

template <typename C, typename E>
inline bool contains(const C& container, const E& element) {
    return container.find(element) != container.end();
}

template <typename K, typename V>
V& updateFromConfig(V& updatee, const K& key, const po::variables_map& vm) {
    if (contains(vm, key)) {
        // option 1
        updatee = vm[key];
        // option 2
        //updatee = vm[key].variable_value();
        // option 3
        // updatee = vm[key].as<V>();
        // option 4
        // updatee = vm[key].as();
    }
    return updatee;
}

template size_t& updateFromConfig<char*,size_t>(size_t& updatee, char* const& key, const po::variables_map& vm);

使用这四个选项中的任何一个,我得到一个不同的编译器错误:

  • 使用选项1:

    cannot convert ‘const boost::program_options::variable_value’ to ‘long unsigned int’ in assignment
       updatee = vm[key];
    
  • 使用选项2:

    invalid use of ‘boost::program_options::variable_value::variable_value’
    
  • 使用选项3:

    18:25: error: expected primary-expression before ‘>’ token
    18:27: error: expected primary-expression before ‘)’ token
    
  • 使用选项4:

    no matching function for call to ‘boost::program_options::variable_value::as() const
    

我做错了什么?

1 个答案:

答案 0 :(得分:2)

胜利的C ++语法。 Do

updatee = vm[key].template as<V>();