gpt4 book ai didi

c++ - 使用 C++17,如何创建类型到值的编译时映射?

转载 作者:行者123 更新时间:2023-11-28 04:08:09 27 4
gpt4 key购买 nike

我正在编写一个包装器库,将真正的 C++ 类型映射到 Java 类型以用于 JNI。为了映射到 JNI 中正确的库调用,我有一系列的类特化:

        template<typename R>
struct call_method_traits;

template<>
struct call_method_traits<void>
{
static constexpr auto value = &JNIEnv::CallVoidMethod;
};

template<>
struct call_method_traits<bool>
{
static constexpr auto value = &JNIEnv::CallBooleanMethod;
};

// etc.....

这是将类型映射到某些值的老式方法,但我想知道在 C++17 中是否有更好的方法。起初,std::tuple 似乎很有前途,但它不是关联类型,所以我不知道如何使用它。

我现在使用的机制仍然是唯一的方法吗?

最佳答案

变量模板会更简单。但是您需要为非特化引入一些默认值:

template <class>
static constexpr auto call_method_traits
= nullptr;

template <>
static constexpr auto call_method_traits<void>
= &JNIEnv::CallVoidMethod;

或者,您可以保留您的特征,只使用变量模板作为别名:

template <class R>
static constexpr auto call_method_traits_v
= call_method_traits<std::decay_t<R>>::value;

这将允许您保留现有 API 的兼容性,但为用户提供更简单的界面。


constexpr 模板函数会更灵活,例如,您可以static_assert 为没有专门化的情况提供简洁的消息。但它涉及更多样板文件。

关于c++ - 使用 C++17,如何创建类型到值的编译时映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58333337/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com