簡體   English   中英

函數調用運算符的 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()第二行)時。 在您的情況下,您需要明確指定返回類型,因為它無法推斷,正確的做法是:

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返回類型來實現您可能想要的,例如

#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作為返回類型,但在更復雜的聲明中可能非常有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM