簡體   English   中英

僅將 2 個功能(模板化)組合在一個中

[英]Combine 2 functions (templated) in only one

我正在嘗試按順序獲得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);
}

我想要的 function 在上面的代碼中被注釋為“組合”。

您可以將boost::hana::string傳遞給 combine( 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);

但是為了啟用boost::hana::literals::operator""_sBOOST_HANA_CONFIG_ENABLE_STRING_UDL在包含<boost/hana/string.hpp>之前定義 BOOST_HANA_CONFIG_ENABLE_STRING_UDL :

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM