问个C++模板问题
各位好。我想写个模板函数,可以任何容器类型(如vector、list、set等),但限制容器元素类型为string。试过以下代码,编译不通过。希望大神帮忙指点。非常感谢。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template <typename C>
void t(C <string>* args)
{
}
int main()
{
vector<string> vi;
t(&vi);
return 0;
}
你想要的这个东西叫concept,很悲催的是本来它应该能进C++17的,但还是被据了……
眼下你能做的就是用static_assert凑合一下,比如:
template<typename C>
void t(C *args) {
static_assert(std::is_same_v<std::string, std::remove_reference_t(decltype(*std::begin(*args)))>, "Error");
}
页:
[1]