我正在尝试制作一个类似于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;
}