gpt4 book ai didi

c++ - 有没有办法将模板函数中允许的类型列入白名单?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:11 25 4
gpt4 key购买 nike

我有一个模板函数,我只想使用特定的类型列表。

 template <class T> void foo(const T f) {/*do stuff with f*/}

int main() {
string A= "Hello world";
char B[10] = "Hello world";
Int C = 69;

foo(A); //should work here
foo(B); //and here
foo(C); //but it should give an error here, preferably while it is compiling

return 0;
}

如果我用 char[] 或字符串调用它,我希望它能工作,但是当我尝试用 INT 类型调用它时会出现错误(可能在编译时,但在运行时也会工作)。

最佳答案

对于您的特殊情况,我会重载函数 foo 而不是使用模板。这确保您只能拥有这两种类型中的一种,特别是对于这两种类型,重载非常简单:

void foo(const char* s) {
// do work with s
}

void foo(const std::string& s) {
foo(s.c_str()); // use the other overload for const char*
}

关于c++ - 有没有办法将模板函数中允许的类型列入白名单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57876446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com