为什么我需要在这里指定模板化函数的模板参数类型?

Ral*_*zky 6 c++ templates c++11

我有以下代码:

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 );
}
Run Code Online (Sandbox Code Playgroud)

在函数中foo()我需要指定模板参数,即使它f1(t)是一个有效的表达式.这有点破坏了我的代码中的一些可能性.我的问题:

  1. 为什么我需要指定模板参数?
  2. 我该如何解决这个限制?(允许使用C++ 11或C++ 14).

(顺便说一句:我目前正在使用Visual Studio 2010,如果我退出,我会收到错误C2896 <T>.)

Rei*_*ica 11

f1不是一个功能,它是一个模板.您不能将模板作为函数参数传递.

f1<T> 是一个函数,所以它可以传递.


Ral*_*zky 8

1.为什么我需要指定模板参数?

好吧,f1不是一个对象,而是一个功能模板.您只能将对象传递给函数.

2.我如何解决这个限制?(允许使用C++ 11或C++ 14).

使用带模板化的对象operator().只需替换f1()with 的定义即可

struct { template <typename T> void operator()( T t )
{
    std::cout << "f1( " << t << " ) called." << endl;
} } f1;
Run Code Online (Sandbox Code Playgroud)

同样地f2().在C++ 14中,您可以更好地编写它

static const auto f1 = []( auto t )
{
    std::cout << "f1( " << t << " ) called." << endl;
};
Run Code Online (Sandbox Code Playgroud)