假设我有一个函数的模板,比方说
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"无效,因此该代码无法编译.那么如何以优雅的方式编写它呢?