【问题标题】:Combine 2 functions (templated) in only one仅将 2 个功能(模板化)组合在一个中
【发布时间】:2021-04-09 00:11:54
【问题描述】:

我正在尝试按插入到元组中的顺序获取boost::hana::string,通过数组中的std::string_view名称查找(请检查代码,那里比我的话更容易理解)。

我明白了,但是语法真的很乱,失去了不言自明的意义,因为需要调用两个函数(1个fn获取索引,1个templ.fn por获取字符串)而不是只有一个直接调用。

请注意,问题比看起来更难,因为boost::hana::string 会返回不同的类型,即使您更改字符串中的单个字符,无论其长度如何。

coliru 中也有源代码:http://coliru.stacked-crooked.com/a/45ea8db0d6b4dbad

#include <array>
#include <tuple>
#include <iostream>
#include <string_view>
#include <boost/hana/string.hpp>

using namespace std::string_view_literals;

constexpr std::array images = { "USERS.PNG"sv, "LESSONS.PNG"sv, "COURSES.PNG"sv, "ALUMNS.PNG"sv };
constexpr std::tuple sources = { BOOST_HANA_STRING("1"), BOOST_HANA_STRING("2"), BOOST_HANA_STRING("3"), BOOST_HANA_STRING("4") };

constexpr size_t image(const std::string_view& name)
{
    size_t i = 0;
    for (auto& image : images)
        if (image == name || !++i) break;

    return i;
}

template <size_t I>
constexpr auto source()
{
    return std::get<I>(sources);
}

//constexpr auto combined(const std::string_view& name)
//{
//    constexpr auto index = image(name);
//    return source<index>();
//}

int main()
{
    //constexpr auto hana_str = combined("LESSONS.PNG"sv);
    
    constexpr auto index = image("LESSONS.PNG"sv);
    constexpr auto hana_string = source<index>();

    static_assert(std::string_view(hana_string.c_str()) == "2"sv);
}

我想要的功能是上面代码中注释为“组合”的功能。

【问题讨论】:

  • 问题是namecombined()的运行时参数。正如你所指出的,source() 的返回类型会根据模板参数I 的值而变化,但是因为combined() 只是一个函数,所以它只能有一个返回类型,而不管@987654332 的值如何@.
  • 是不是说这个问题在编译时使用单个函数是无法解决的?有人知道达到此目的的其他策略(例如 boost::hana::map 或我可能跳过的某些字符串)吗?
  • 这是一个可能的解决方案:godbolt.org/z/7KWT8hjsq
  • @Patrick Roberts:谢谢,这很聪明。您正在使用可以在编译时解决的字符串并将其作为模板参数传递,以便在调用新名称时生成不同的函数。对我来说很好,您想将您的评论升级为答案以便人们投票吗?
  • 我不明白问题标题中的“2 x 1”应该是什么意思。

标签: c++ templates c++17 boost-hana


【解决方案1】:

您可以将boost::hana::string 传递给combined(),以便在编译时使用std::string_view 调用image()

template <class CharT, CharT... s>
constexpr auto combined(const boost::hana::string<s...>& name)
{
   constexpr auto index = image(name.c_str());
   return source<index>();
}

下面是如何使用它:

using boost::hana::literals::operator""_s;
constexpr auto hana_str = combined("LESSONS.PNG"_s);
static_assert(hana_str.c_str() == "2"sv);

但是in order to enable boost::hana::literals::operator""_s you need to define BOOST_HANA_CONFIG_ENABLE_STRING_UDL之前包括&lt;boost/hana/string.hpp&gt;

#define BOOST_HANA_CONFIG_ENABLE_STRING_UDL
#include <boost/hana/string.hpp>

【讨论】:

  • 另外,作为题外话,只是说_s 在 MS Visual Studio 2017 或更低版本中不起作用,很遗憾。无论如何,您的解决方案仍然有效,由BOOST_HANA_STRING(string) 调用它虽然稍微冗长一些。
猜你喜欢
  • 2019-07-13
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多