antigloss 发表于 2016-09-14 18:07

问个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;
}


windoze 发表于 2016-09-17 01:34

你想要的这个东西叫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]
查看完整版本: 问个C++模板问题