我有一个函数 f
:
template <typename T>
void f(T<int> ints)
{ /* */ }
这个函数应该使用 std::vector<int>
或 std::initializer_list<int>
或任何其他 STL 容器,但前提是它包含 int
.
我可以忍受接受其他 class
es 与 int
作为模板参数,但我不希望它接受 std::vector<char>
或 std::vector<double>
或 std::list<double>
或类似的东西。
我怎样才能意识到这一点?
最佳答案
您可以使用模板模板参数:
template <template <typename...> typename T>
void f(const T<int>& ints)
{ /* */ }
但我建议改用容器的 value_type
类型成员。这将避免将其他模板与 int
作为模板参数进行匹配。
//using std::enable_if_t
template <typename T>
std::enable_if_t<std::is_same<typename T::value_type, int>::value>
f(const T& ints)
{ /* */ }
//or static_assert
template <typename T>
void f(const T& ints) {
static_assert(std::is_same<typename T::value_type, int>::value,
"T must be a container of ints");
//...
}
关于c++ - 包含特定对象的 STL 容器模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35865707/