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