c++ - 将类型特征与可变参数模板参数一起使用

标签 c++ templates c++17 variadic-templates variadic

我正在尝试制作一个功能类似于 python 打印函数的打印函数,但我在强制执行可变参数可以是什么类型方面遇到了问题,我希望它们被限制为 const char*.

到目前为止,这是我的代码:

#include <tuple>
#include <iostream>
#include <utility>
#include <type_traits>


template<
  std::size_t I=0,
  typename... Args,
  typename FUNCTION
  >
constexpr void for_each(const std::tuple<Args...>& t, FUNCTION &&func)
{
  if constexpr(I < sizeof...(Args))
  {
    func(std::get<I>(t));
    for_each<I + 1>(t, std::forward<FUNCTION>(func));
  }
}

template<
  typename... Args
  >
constexpr void print(Args... args)
{
  std::tuple t(std::forward<Args>(args)...);
  for_each(t, [=](const char* str)
  {
    std::cout << str << " ";
  });
  std::cout << '\n';
}

int main(void)
{
  print("this", "is", "a", "thing");
  print("this", "is", "not", "a", "thing");
  return 0;
}

我希望 print 函数中的可变模板参数只接受 const char*

最佳答案

你不需要std::tuple这样做你可以限制你的功能复制const char*仅使用 std::enable_if ,如下

#include <iostream>
#include <type_traits>


template<typename ... Args>
constexpr std::enable_if_t<std::is_same_v<std::common_type_t<Args...>,const char*>, void>
print(Args&&... args)
{
    ((std::cout << args << " "),...);
    std::cout << '\n';
}
int main( )
{
    print("this", "is", "a", "thing");
    print("this", "is", "not", "a", "thing");
    print(5, "is", "not", "a", "thing");//compile error
    return 0;
}

关于c++ - 将类型特征与可变参数模板参数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62775308/

相关文章:

c++ - 计算以字节为单位的位数

c++ - 从折叠表达式创建一个带分隔符的字符串

c++ - 将 "this"动态转换为返回值是否可以?

c++ - boost 图 : How to copy the nodes and edges of a graph without copying properties?

c++ - error C2512 没有合适的默认构造函数可用

c++ - 在cpp中重定向stdout输出

java - 在 Java 编辑器模板中开始为空白

javascript - 如何在登录模板周围添加不​​同的图标?

c++ - 如何将 std::atomic<T>::is_always_lock_free 用于 SFINAE?

c++ - 在 std::variant 中隐藏模板参数