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);
}
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…