次のように、関数テンプレートが非 const 左辺値の場合に左辺値性を維持しながら引数を転送する必要があるが、それ自体は引数が実際に何であるかにとらわれない状況を考えてみましょう。
template <typename T>
void target(T&) {
cout << "non-const lvalue";
}
template <typename T>
void target(const T&) {
cout << "const lvalue or rvalue";
}
template <typename T>
void forward(T& x) {
target(x);
}
x
が右辺値の場合T
、定数型に推定されるのではなく、エラーが発生します。
int x = 0;
const int y = 0;
forward(x); // T = int
forward(y); // T = const int
forward(0); // Hopefully, T = const int, but actually an error
forward<const int>(0); // Works, T = const int
右辺値を (明示的forward
なテンプレート引数を呼び出さずに) 処理するには、forward(const T&)
本体が完全に複製されていても、オーバーロードが必要なようです。
この重複を避ける方法はありますか?