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

C++ template for function call operator

我尝试使用模板进行函数调用运算符重载,如下程序所示:

#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;
}

虽然第二次打印中的值函数调用没有显示任何错误,但第一次打印中的函数调用运算符显示 expected primary-expression 错误。我不知道我做错了什么。任何人都可以帮助我提前知道问题。

问题出在调用模板化 operator() 时(main() 的第二行)。在您的情况下,您需要明确指定 return 类型,因为它无法推导出来,正确的做法是:

printf("Value : %d\n", apple.operator()<int>());

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

定义这样的运算符有用吗?可能不会,因为它会导致语法难看。


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

#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;
}

在此示例中,auto 并没有真正发挥作用,因为您可以手动将 int 指定为 return 类型,但在更复杂的声明中可能非常有用。