首页 > 解决方案 > 如何使用模板参数包实现 SFINAE 仅限于少数类型

问题描述

我需要启用 std::string 和 int,但使用参数包。

template <typename... ParamType, typename = typename std::enable_if<std::is_same<ParamType..., std::string>::value || std::is_same<ParamType..., int>::value>::type>
static inline void Log(const ParamType & ... args)
{

}

但我打电话时出错

Log("hello"s, "world"s); //syntax ERROR 

期望的结果

Log(4,3,"Hello"s); //OK
Log("Hello"s); //OK
Log(5); //OK

标签: c++visual-c++c++17

解决方案


该解决方案使用了一些 C++17-ism ( std::void_t)。如果需要,它们的各种实现适用于随处可见的早期 C++ 标准:

template <typename ... ParamType,
      typename = std::void_t<std::enable_if_t
                 <std::is_same_v<ParamType, std::string> ||
                  std::is_same_v<ParamType, int>>...>>
static inline void Log(const ParamType & ... args)
{

}

推荐阅读