如何避免使用类模板专门化的代码重复 [英] How to avoid code duplicates with class template specializations
本文介绍了如何避免使用类模板专门化的代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想避免以下代码中的重复项.
I'd like to avoid the duplicates in the code below.
#include <iostream>
struct Bar{};
template <class... Args>
struct FooClass;
template <class... Args>
inline void foo(Args&&... args) {
FooClass<Args...>::impl(std::forward<Args>(args)...);
}
// Duplicate 1.
// Const ref version
template <>
struct FooClass<Bar const&> {
inline static void impl(const Bar& b) {
std::cout << "dup1" << std::endl;
}
};
// Duplicate 2.
// Copy version
template <>
struct FooClass<Bar> {
inline static void impl(const Bar& b) {
std::cout << "dup2" << std::endl;
}
};
// Duplicate 3.
// Non-const ref version
template <>
struct FooClass<Bar&> {
inline static void impl(const Bar& b) {
std::cout << "dup3" << std::endl;
}
};
int main()
{
const Bar b2;
foo(b2);
foo(Bar{});
Bar b;
foo(b);
}
我很确定可以通过某种方式使用enable_if和通用引用来实现,但我无法弄清楚.
I'm pretty sure this is possible using enable_if and universal references somehow, but I could not figure it out.
顺便说一句,该程序输出:
Btw., this program outputs:
dup1
dup2
dup3
如果注释掉这三个专业中的任何一个,它都不会编译.
and it won't compile if any of the three specializations are commented out.
推荐答案
为什么不从模板参数中删除 const
和&
?
Why not just strip off const
and &
from the template argument?
template<class... Args>
void foo(Args&&... args) {
FooClass<std::decay_t<Args>...>::impl(std::forward<Args>(args)...);
// ^^^^^^^^^^^^
}
template<>
struct FooClass<Bar> {
static void impl(const Bar&) {
std::cout << "bar" << std::endl;
}
};
int main() {
const Bar b2;
foo(b2); // prints "bar"
foo(Bar{}); // prints "bar"
Bar b;
foo(b); // prints "bar"
}
这篇关于如何避免使用类模板专门化的代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文