【发布时间】:2021-08-12 02:10:15
【问题描述】:
我对这三件事感到困惑。这是一个简单的例子:
template<typename T>
void func(T t) {
if (typeid(T) == typeid(int)) {
std::cout << "f - int" << std::endl;
} else {
std::cout << "f - other" << std::endl;
}
}
template<typename T>
void func2(T t) {
if (std::is_same<T, int>::value) {
std::cout << "f2 - int" << std::endl;
} else {
std::cout << "f2 - others" << std::endl;
}
}
template<typename T>
void func3(T t) {
if constexpr (std::is_same<T, int>::value) {
std::cout << "f3 - int" << std::endl;
} else {
std::cout << "f3 - other" << std::endl;
}
}
int main() {
func(1);
func('a');
func2(1);
func2('a');
func3(1);
func3('a');
return 0;
}
输出是
f - int
f - others
f2 - int
f2 - others
f3 - int
f3 - others
所以它按预期工作。但我有点不知道在哪种情况下应该使用哪个。
据我了解,第一个中的typeid 完全是关于运行时的。这是我知道的全部。但是模板是关于编译时间的,对吧?那么这是否意味着func 是一个愚蠢的设计?
func2 和func3 怎么样?它们完全一样吗?它们都是关于编译时间的吗?或者func2 仍然是关于运行时的?
【问题讨论】:
标签: c++11 templates c++17 runtime if-constexpr