hgi*_*sel 1 c++ containers templates stl
我有一个功能f:
template <typename T>
void f(T<int> ints)
{ /* */ }
Run Code Online (Sandbox Code Playgroud)
该函数应该采用std::vector<int>或std::initializer_list<int>任何其他STL容器,但仅限于它包含int.
我可以用它收受他人生活classES与int作为模板参数,但我不希望它接受std::vector<char>或std::vector<double>或std::list<double>或这样的事情.
我怎么能意识到这一点?
您可以使用模板模板参数:
template <template <typename...> typename T>
void f(const T<int>& ints)
{ /* */ }
Run Code Online (Sandbox Code Playgroud)
但我建议使用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");
//...
}
Run Code Online (Sandbox Code Playgroud)