如何为相同类型的参数启用自动非类型模板参数包
How to enable auto nontype template parameter pack for same type of parameters
我有以下代码:
template<auto... args> struct Custom
{
};
int main()
{
Custom<1, nullptr> s; // i want this to succeed only when all the template arguments are of the same type
}
从上面的代码可以看出,我可以传递不同类型的模板参数。我的问题是有没有办法只接受相同类型的模板参数。这意味着 main
中的语句应该失败,并且只有在所有模板参数都属于同一类型时才有效。本质上,有 2 个要求:
- 该代码不适用于少于 1 个模板参数。也就是说,必须至少存在一个模板参数。如果用户提供 0 个模板参数,则它不应该工作。
- 该代码不适用于不同类型的模板参数。
即使可能,我也不会。我正在考虑使用 enable_if
或其他一些功能,但我不知道这里有什么帮助。
您可以使用 decltype
结构,如下所示:
template<auto T1, decltype(T1)... Args> struct Custom
{
};
C++17 中的简单方法是使用 static_assert
#include <type_traits>
template<auto first, auto... rest>
struct Custom {
static_assert(
(std::is_same_v<decltype(first), decltype(rest)> && ...),
"non-type template parameter pack must be the same type.");
};
在 C++20 中,您可以只使用概念:
#include <concepts>
template<auto first, auto... rest>
requires (std::same_as<decltype(first), decltype(rest)> && ...)
struct Custom {
};
我有以下代码:
template<auto... args> struct Custom
{
};
int main()
{
Custom<1, nullptr> s; // i want this to succeed only when all the template arguments are of the same type
}
从上面的代码可以看出,我可以传递不同类型的模板参数。我的问题是有没有办法只接受相同类型的模板参数。这意味着 main
中的语句应该失败,并且只有在所有模板参数都属于同一类型时才有效。本质上,有 2 个要求:
- 该代码不适用于少于 1 个模板参数。也就是说,必须至少存在一个模板参数。如果用户提供 0 个模板参数,则它不应该工作。
- 该代码不适用于不同类型的模板参数。
即使可能,我也不会。我正在考虑使用 enable_if
或其他一些功能,但我不知道这里有什么帮助。
您可以使用 decltype
结构,如下所示:
template<auto T1, decltype(T1)... Args> struct Custom
{
};
C++17 中的简单方法是使用 static_assert
#include <type_traits>
template<auto first, auto... rest>
struct Custom {
static_assert(
(std::is_same_v<decltype(first), decltype(rest)> && ...),
"non-type template parameter pack must be the same type.");
};
在 C++20 中,您可以只使用概念:
#include <concepts>
template<auto first, auto... rest>
requires (std::same_as<decltype(first), decltype(rest)> && ...)
struct Custom {
};