函数调用运算符的C ++模板 [英] C++ template for function call operator
问题描述
我尝试将模板用于函数调用运算符的重载,如以下程序所示:
I tried to use template for function call operator overload as in the following program:
#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
错误.我不知道我在做什么错.任何人都可以帮助我知道这个问题,谢谢.
While value function call in the second print does not show any error the function call operator in the first print show expected primary-expression
error. I don't know what I am doing wrong. Can anyone help me know the problem thanks in advance.
推荐答案
问题在于调用模板化的operator()
(main()
的第二行)时.在您的情况下,您需要显式指定返回类型,因为无法推断出返回类型,正确的执行方式是:
The problem is when invoking a templated operator()
(second line of main()
). In your case, you need to explicitly specify the return type, as it cannot be deduced, and the correct way of doing it is:
printf("Value : %d\n", apple.operator()<int>());
operator()()
是采用()
作为参数的模板成员函数.因此,其名称为operator()
,其参数列表为()
.因此,要引用它,您需要使用apple.operator()
(其名称),然后使用<int>
(模板参数),然后使用()
(参数列表).将名称operator()
替换为FUNCTION
,因此operator()()
为FUNCTION()
,您将看到该模式.在您的情况下,apple<int>()
正在调用模板实例化apple<int>
对象(即apple<int>.operator()()
)上的非模板operator()()
,这不是您想要的.
operator()()
is a template member function that takes ()
as parameters. So, its name is operator()
, its parameter list is ()
. Therefore, to refer to it, you need to use apple.operator()
(its name), followed by <int>
(template parameter), then followed by ()
(parameter list). Replace mentally the name operator()
with FUNCTION
, so operator()()
is FUNCTION()
, and you'll see the pattern. In your case, apple<int>()
is invoking a non-template operator()()
on a template instantiation apple<int>
object, i.e. apple<int>.operator()()
, which is not what you want.
对定义这样的运算符有用吗?可能不是,因为它会导致语法丑陋.
Useful to define such an operator? Probably not, as it leads to ugly syntax.
您可以通过在C ++ 14中使用auto
返回类型来实现您可能想要的目标,例如
You can achieve what you probably want by using auto
return type in C++14, like
#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
指定为返回类型,但是在更复杂的声明中会非常有用.
In this example, auto
doesn't really shine, as you may manually specify int
as the return type, but in more complicated declaration can be really useful.
这篇关于函数调用运算符的C ++模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!