首页 > 解决方案 > 如何访问相同特征 C++ 的不同特征特化?

问题描述

我正面临这个让我发疯的问题。我有一个模板结构,能够提供部分专业化:

template <typename ReturnType>
struct field {
  template <typename MessateType>
  inline static ReturnType get(MessateType const& message, int const field) {
    static_assert(false, "Missing trait specialization for the given type");
  }
};

现在。我希望这个通用的让我知道我是否正在尝试将它与不受支持的类型一起使用。到目前为止,一切都很好。

有了这个,我需要将它专门用于 int:

template <>
struct field<int> {
  template <typename MessateType>
  inline static int get(MessateType const& message, int const field) {
    return std::atoi(message.getField(field).c_str());
  }
};

现在,除了为了简洁起见我正在削减的其他一些类型之外,我需要专门对它进行提升:可选。为此,我正在尝试以下代码:

template <typename T>
struct field<optional<T>> {
  template <typename MessateType>
  inline static optional<T> get(MessateType const& message, int const field) {
    return message.isSetField(field) ? field<T>::get(message, field)
                                     : optional<T>(boost::none);
  }
};

但是,我在编译器上收到以下错误:

error C2275: 'T': illegal use of this type as an expression
error C2039: 'get': is not a member of '`global namespace''

我一直在寻找解决方案,但我无法找到它。看起来编译器不喜欢我试图int从另一个特征 ( ) 访问其中一个特征 ( )的事实optional<int>

标签: c++c++11compiler-errorstraitstypetraits

解决方案


TC 的评论“重命名你的第二个函数参数”。是解决这个问题:

我将其更改为:

template <typename T>
struct field<optional<T>> {
  template <typename MessateType>
  inline static optional<T> get(MessateType const& message, int const field_id) {
    return message.isSetField(field_id) ? field<T>::get(message, field_id)
                                        : optional<T>(boost::none);
  }
};

它完美地工作。非常感谢!


推荐阅读