簡體   English   中英

關於C ++模板和運算符

[英]About C++ template and operators

經過一番嘗試和許多錯誤之后,我發現它對模板運算符不是很有用。 舉個例子:

class TemplateClass
{
  //Generalized template
  template<TType>
  TType& operator[](const std::string& key)
  {
    return TType;
  }
  //Specialized template for int
  template<>
  int& operator[]<int>(const std::string& key)
  {
    return 5;
  }
  //Specialized template for char
  template<>
  char& operator[]<char>(const std::string& key)
  {
    return 'a';
  }
}
int main()
{
  TemplateClass test;
  //this will not match the generalized template.
  test["test without template will fail"]; 
  //this is not how you call an operator with template.
  test<char>["test with template will fail"];
  //this works!
  test.operator[]<int>["test will work like this"];
  return 0;
}

因此,使用模板使運算符非常丑陋(除非您很冗長,而實際上是誰?)這就是為什么我一直使用函數“ get”代替運算符的原因。 我的問題是為什么要丑陋? 為什么需要包含操作員關鍵字。 我的猜測是,這與轉換運算符以不使用括號來接受參數有關的后端魔術有關,這有什么辦法嗎? 提前致謝。

這不是模板的特別問題。 這是一個語法問題。 您所做的事情很奇怪,因為您僅更改返回類型。 如果您更改了操作員參數,則無需顯式提供模板的類型。 由於確實需要提供類型,因此您需要顯式調用運算符以應用參數,因為這是唯一的方法。

查看語法以獲取完整的詳細信息。

返回類型不能用於重載分辨率。 您的operator []聲明的簽名的唯一區別在於它們的返回類型,因此,一旦您擁有其中的兩個,編譯器就沒有希望消除您的調用test["test without template will fail"];的歧義test["test without template will fail"];

是的,模板參數推導不能簡單地與函數返回類型一起使用。 但是,模板運算符重載確實很有用,並且可以以某些完全巨大的方式應用。

下面是boost :: phoenix的代碼示例。

for_each(c.begin(), c.end(),
    if_(arg1 % 2 == 1)
    [
        cout << arg1 << ' '
    ]
);

如您所知,這是一種打印容器中所有奇數元素的簡便方法。 有點神奇。

暫無
暫無

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

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