我正在尝试创建一个可以用作...的函数 foobar()
int main()
{
auto x = foobar(__func__);
// decltype(x) = std::integer_sequence<char, 'm', 'a', 'i', 'n'>
}
有什么提示吗?
该代码不需要需要在 MSVC 上运行。
最佳答案
我看到的问题是将 __func__
作为函数参数传递
foobar(__func__);
我没有找到根据 __func__
的值更改 foobar()
返回类型的方法。
如果将 __func__
作为模板参数传递,则不同,但 __func__
是字符串文字,而字符串文字(据我所知)不能是模板参数C++20 之前。
但是...如果您接受 C++20 解决方案,其中 __func__
作为模板参数传递...我想您可以编写如下内容
#include <utility>
#include <array>
template <std::size_t N>
struct bar
{
using index_type = std::make_index_sequence<N-1u>;
std::array<char, N-1u> arr;
template <std::size_t ... Is>
constexpr bar (std::index_sequence<Is...>, char const (&a0)[N]) : arr{a0[Is]...}
{ }
constexpr bar (char const (&a0)[N]) : bar{index_type{}, a0}
{ }
};
template <bar b, std::size_t ... Is>
constexpr auto baz (std::index_sequence<Is...>)
-> std::integer_sequence<char, b.arr[Is]...>
{ return {}; }
template <bar b>
constexpr auto foo ()
{ return baz<b>(typename decltype(b)::index_type{}); }
int main ()
{
using target_type = std::integer_sequence<char, 'm', 'a', 'i', 'n'>;
constexpr auto x = foo<__func__>();
static_assert( std::is_same_v<decltype(x), target_type const> );
}
关于c++ - 如何从 `std::integer_sequence` 创建 `__func__` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64126774/