c++ - 如何从 `std::integer_sequence` 创建 `__func__` ?

标签 c++ variadic-templates template-meta-programming constexpr

我正在尝试创建一个可以用作...的函数 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/

相关文章:

c++ - 来自 .h 和 .cpp 的条件编译

c++ - 如何将字符转换为整数

为非虚拟方法指定的c++初始化

c++ - 在 C++ 中检测运算符是否存在和可调用(考虑 static_asserts)

c++ - 每次我在 visual studio 2015 中构建时出现权限错误

c++ - 在没有代码重复的情况下将 C 函数包装在自动对象中

c++ - 参数包是模板参数吗?

c++ - 简化模板参数

c++ - 如何用通用 TR1 函数对象包装多个函数重载?

c++ - 使用具有非 constexpr 值的 int 模板函数