我玩了一點轉發,並得到以下示例,它工作正常。rvalue和左值引用的模板專門化
void Func2(int& a, int& b) { cout << "V1" << endl; }
void Func2(int&& a, int& b) { cout << "V2" << endl; }
void Func2(int& a, int&& b) { cout << "V3" << endl; }
void Func2(int&& a, int&& b) { cout << "V4" << endl; }
template < typename T, typename U>
void Func(T&& t, U&& u)
{
X::Func3(std::forward<T>(t), std::forward<U>(u));
Func2(std::forward<T>(t), std::forward<U>(u));
}
int main()
{
int a, b;
Func(a, b);
Func(1, b);
Func(a, 2);
Func(1, 2);
return 0;
}
但我想也有Func2
函數模板與任何類型的,或者無法與專門方法的類來代替類型int
。下面的代碼片段不會編譯:
class X
{
public:
template < typename T, typename U>
static void Func3(T& t, U& u) { cout << "X1" << endl; }
template < typename T, typename U>
static void Func3(T&& t, U& u) { cout << "X2" << endl; }
template < typename T, typename U>
static void Func3(T& t, U&& u) { cout << "X3" << endl; }
template < typename T, typename U>
static void Func3(T&& t, U&& u) { cout << "X4" << endl; }
};
結果:
main.cpp: In instantiation of 'void Func(T&&, U&&) [with T = int&; U = int&]':
main.cpp:36:18: required from here
main.cpp:29:57: error: call of overloaded 'Func3(int&, int&)' is ambiguous
X::Func3(std::forward<T>(t), std::forward<U>(u));
^
main.cpp:29:57: note: candidates are:
main.cpp:9:29: note: static void X::Func3(T&, U&) [with T = int; U = int]
static void Func3(T& t, U& u) { cout << "X1" << endl; }
^
main.cpp:12:29: note: static void X::Func3(T&&, U&) [with T = int&; U = int]
static void Func3(T&& t, U& u) { cout << "X2" << endl; }
^
main.cpp:15:29: note: static void X::Func3(T&, U&&) [with T = int; U = int&]
static void Func3(T& t, U&& u) { cout << "X3" << endl; }
^
main.cpp:18:29: note: static void X::Func3(T&&, U&&) [with T = int&; U = int&]
static void Func3(T&& t, U&& u) { cout << "X4" << endl; }
^
請添加編譯器錯誤消息。 – BoBTFish