【发布时间】:2014-06-03 15:09:13
【问题描述】:
我知道如何使用模板处理任何数据类型:
template<typename T>
T myFunc(T data) { ... }
但是有没有办法将允许的类型集缩小到例如int 和char 或std::string 和std::wstring,所以编译器在遇到不允许的参数类型时会抛出错误,我会在编译时而不是运行时出错?
编辑:非常感谢 ecatmur,现在我理解了整个概念。
template<typename itemA_type, typename itemB_type>
typename std::enable_if<
(
std::is_same<itemA_type, int>::value ||
std::is_same<itemA_type, char>::value) &&
(
std::is_same<itemB_type, std::string>::value ||
std::is_same<itemB_type, std::wstring>::value ||
std::is_same<itemB_type, const char*>::value ||
std::is_same<itemB_type, const wchar_t*>::value
) ,
void
>::type
myFunction(itemA_type itemA, itemB_type itemB) {
using namespace std;
cout << itemA << itemB << endl;
}
【问题讨论】:
-
是否可以使用 C++11 的特性?
-
这可以通过以下
DeadMG描述的任何方式以临时方式完成。有关库解决方案,请参阅Boost.ConceptCheck(以及其他)。 -
为什么是模板,如果你可以用四种所需的参数类型重载函数???
-
@Massa One 可以使用重载,但在这种情况下,应该执行很多复制+粘贴操作。
标签: c++ function templates c++11 polymorphism