小编dud*_*ulu的帖子

如何在C++中比较两个类型名称是否相等?

假设我有一个函数的模板,比方说

template<typename T>
func(T a, T b, ...) {
  ...
  for (const auto &single : group) {
    ...
    auto c = GivenFunc1(a, b, single, ...);
    ...      }
  ...
}
Run Code Online (Sandbox Code Playgroud)

但是,对于T是一种特殊类型,比如说"SpecialType",我希望c通过"GivenFunc2"而不是"GivenFunc1"来计算.但是,我不想为"SpecialType"编写专门化,因为会有大量的代码重复.所以我想模板功能就像

template<typename T>
func(T a, T b, ...) {
  ...
  for (const auto &single : group) {
    ...
    auto c = (T == SpecialType) ? GivenFunc2(a, b, single, ...)
                                : GivenFunc1(a, b, single, ...);
    ...      }
  ...
}
Run Code Online (Sandbox Code Playgroud)

当然,由于"T == SpecialType"无效,因此该代码无法编译.那么如何以优雅的方式编写它呢?

c++ templates

25
推荐指数
4
解决办法
2307
查看次数

标签 统计

c++ ×1

templates ×1