c++ - 如何访问相同特征 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>
。
解决方案
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);
}
};
它完美地工作。非常感谢!
推荐阅读
- excel - 提高循环性能的速度?
- django - 如何在 CreateView 中将字段设为只读
- c# - C#如何在Task.WhenAll中捕获任务结果?“.Result”或“等待”
- python - 当有使用 Django 的可用选项时,如何使依赖下拉列表成为必需?
- macos - 在 Mac 上运行 Visual Studio Code 时出现问题
- c# - 大写 JSON 键
- android - 如何将 FirestoreDocumentReference 放入 CloudFirestore 中的类型映射字段
- django - Docker 应用服务器 ip 地址 127.0.0.1 差 0.0.0.0 ip
- reactjs - 反应 redux 容器将状态发送到另一个容器
- django - Django:在视图中访问 num_pages 以生成分页