【发布时间】:2013-06-18 12:58:27
【问题描述】:
我有以下代码:
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> necessary?
// f1(t) is a valid expression!
call( f2<T>, t );
}
void bar()
{
foo( 1 );
}
在函数foo() 中我需要指定模板参数,即使f1(t) 是一个有效的表达式。这有点破坏我的代码中的一些可能性。我的问题:
- 为什么需要指定模板参数?
- 如何解决这个限制? (允许使用 C++11 或 C++14)。
(顺便说一句:我目前使用的是 Visual Studio 2010,如果我不使用 <T>,则会收到错误 C2896。)
【问题讨论】: