函数调用运算符的C++模板

Din*_*esh 7 c++ templates operator-overloading

我尝试使用模板进行函数调用操作符重载,如下面的程序:

#include <stdio.h>

struct Apple
{
   template <typename tn> tn value ();
   template <typename tn> tn operator () ();
};

template <> int Apple::value ()
{
   return 10;
}

template <> int Apple::operator () ()
{
   return 10;
}

int main()
{
   Apple apple;
   printf("Value : %d\n", apple<int>());
   printf("Value : %d\n", apple.value<int>());   
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

当第二次打印中的值函数调用未显示任何错误时,第一次打印中的函数调用操作符显示expected primary-expression错误.我不知道我做错了什么.任何人都可以提前帮助我知道这个问题.

vso*_*tco 11

问题是在调用模板化operator()(第二行main())时.在您的情况下,您需要显式指定返回类型,因为它无法推断,并且正确的方法是:

printf("Value : %d\n", apple.operator()<int>());
Run Code Online (Sandbox Code Playgroud)

operator()()是一个模板成员函数,它()作为参数.所以,它的名字是operator(),它的参数列表是().因此,要引用它,您需要使用apple.operator()(其名称),然后使用<int>(模板参数),然后使用()(参数列表).更换精神上的名字operator()FUNCTION,所以operator()()就是FUNCTION(),你会看到的模式.在您的情况下,apple<int>()operator()()在模板实例化apple<int>对象上调用非模板,即apple<int>.operator()(),这不是您想要的.

有用的定义这样的运算符?可能不会,因为它导致丑陋的语法.


你可以通过auto在C++ 14中使用返回类型来实现你可能想要的东西,比如

#include <stdio.h>

struct Apple
{
   template <typename tn> tn value ();
   auto operator () ();
};

template <> int Apple::value ()
{
   return 10;
}

auto Apple::operator () () // not a template anymore, return type is deduced int
{
   return 10;
}

int main()
{
   Apple apple;
   printf("Value : %d\n", apple());
   printf("Value : %d\n", apple.value<int>());   
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,auto并没有真正闪耀,因为你可以手动指定int为返回类型,但在更复杂的声明中可能真的很有用.