作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一个模板函数,我只想使用特定的类型列表。
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/
我是一名优秀的程序员,十分优秀!