以下のコードの重複を避けたいと思います。
#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とユニバーサル参照を使用してこれが可能であると確信していますが、理解できませんでした。
ところで、このプログラムは以下を出力します:
dup1
dup2
dup3
3つの専門分野のいずれかがコメントアウトされている場合はコンパイルされません。
理由だけ取り除くないconst
と&
テンプレート引数から?
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"
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加