我最近接触过这个问题,答案可以概括为"这是一个非受限的背景".
具体来说,第一个说它是这样的东西,然后重定向到"细节"的标准,而第二个引用标准,这至少可以说是神秘的.
有人可以向凡人解释,比如我自己,什么是非受限的背景,什么时候发生,为什么会发生?
c++ templates template-argument-deduction argument-deduction
这段代码有什么问题?
#include <map>
template<typename T>
struct TMap
{
typedef std::map<T, T> Type;
};
template<typename T>
T test(typename TMap <T>::Type &tmap_) { return 0.0; }
int _tmain(int argc, _TCHAR* argv[])
{
TMap<double>::Type tmap;
tmap[1.1] = 5.2;
double d = test(tmap); //Error: could not deduce template argument for T
return 0;
}
Run Code Online (Sandbox Code Playgroud) 请考虑以下代码:
#include <iostream>
template<class T>
struct outer {
struct inner {};
};
template<class T>
std::ostream& operator<<(std::ostream & stream,
typename outer<T>::inner const& value) {
std::cout << "An outer::inner!";
return stream;
}
int main() {
outer<float>::inner foo;
std::cout << foo << std::endl; // does not compile
}
Run Code Online (Sandbox Code Playgroud)
这不编译,因为typename outer<T>::inner是nondeduced背景(如解释在这里),这意味着模板参数的类型不能被编译器推导出(读这个答案的原因).在我看来,我有两个选项让它工作:
inner到外面outer并使其成为类模板.我更喜欢这个,因为对使用代码的影响较小.to_string在内部添加一个方法.是否有任何其他解决方案(在使用代码中不会导致丑陋的语法)?
我有以下代码:
template <typename T>
void f1( T t )
{
std::cout << "f1( " << t << " ) called." << endl;
}
template <typename T>
void f2( T t )
{
std::cout << "f2( " << t << " ) called." << endl;
}
template <typename F, typename T>
void call( F && f, T t )
{
f( t );
}
template <typename T>
void foo( T t )
{
call( f1<T>, t ); // Why is <T> …Run Code Online (Sandbox Code Playgroud)