【发布时间】:2014-02-14 09:53:43
【问题描述】:
我玩了一下转发,得到了下面的例子,它工作得很好。
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; }
^
【问题讨论】:
-
请添加编译器错误信息。
标签: c++ templates c++11 overloading rvalue-reference