【问题标题】:Implement of BOOST_DEDUCED_TYPENAME without Boost没有 Boost 的 BOOST_DEDUCED_TYPENAME 的实现
【发布时间】:2014-12-14 00:28:09
【问题描述】:

有如下代码sn-p:

template<typename ValueType>
ValueType any_cast(any & operand)
{
    typedef BOOST_DEDUCED_TYPENAME remove_reference<ValueType>::type nonref;


    nonref * result = any_cast<nonref>(&operand);
    if(!result)
        boost::throw_exception(bad_any_cast());

    // Attempt to avoid construction of a temporary object in cases when 
    // `ValueType` is not a reference. Example:
    // `static_cast<std::string>(*result);` 
    // which is equal to `std::string(*result);`
    typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_<
        boost::is_reference<ValueType>,
        ValueType,
        BOOST_DEDUCED_TYPENAME boost::add_reference<ValueType>::type
    >::type ref_type;

    return static_cast<ref_type>(*result);
}

是否有可能在没有Boost 的情况下实现BOOST_DEDUCED_TYPENAME?我只能使用C++11

【问题讨论】:

  • typename 关键字有什么问题?
  • @remyabel,你能举出typename 的例子吗?

标签: c++ c++11 boost metaprogramming template-meta-programming


【解决方案1】:

如果您有支持 C++11 的编译器,我发现您不太可能需要 BOOST_DEDUCED_TYPENAME。即,它位于include/boost/config/suffix.hpp:

// BOOST_DEDUCED_TYPENAME workaround ------------------------------------------//
//
// Some compilers don't support the use of `typename' for dependent
// types in deduced contexts, e.g.
//
//     template <class T> void f(T, typename T::type);
//                                  ^^^^^^^^
// Replace these declarations with:
//
//     template <class T> void f(T, BOOST_DEDUCED_TYPENAME T::type);

#ifndef BOOST_NO_DEDUCED_TYPENAME
#  define BOOST_DEDUCED_TYPENAME typename
#else
#  define BOOST_DEDUCED_TYPENAME
#endif

只需使用typename 关键字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多