簡體   English   中英

帶有 const ref 參數的函數模板特化

[英]Function template specialization with const ref arguments

下面的代碼編譯得很好

#include <iostream>

struct rgb8{
    uint8_t r() const {return 0;};
};


template<typename L, typename P>
L pixelToLevel(P p) {
    return static_cast<L>(p);
}

template<>
uint8_t pixelToLevel<uint8_t, rgb8>(rgb8 p) {  //       <---------- line X
    return pixelToLevel<uint8_t, uint8_t>(p.r());
}


int main()
{
  pixelToLevel<uint8_t>(rgb8());
  return 0;
}

但是如果在第 XI 行rgb8 p更改為const rgb8& p ,它將無法編譯。

(生成的確切編譯器錯誤取決於顯式模板參數rgb8是否也更改為const rgb8& 。)

如果我想通過引用而不是 X 行上的值傳遞p ,我該如何編譯它?

您需要更改特化聲明中的模板參數,調用它時也需要更改模板參數。 否則將調用主模板。 例如

template<>
uint8_t pixelToLevel<uint8_t, const rgb8&>(const rgb8& p) {  //       <---------- line X
    return pixelToLevel<uint8_t, uint8_t>(p.r());
}

然后

pixelToLevel<uint8_t, const rgb8&>(rgb8());

居住


編輯

鑒於pixelToLevel<uint8_t>(rgb8()); , 模板rgb8推導使用主模板進行, P推導為rgb8 (它不會推導出為const rgb8&與當前主模板的參數聲明),那么特化版本將不會被調用。

您可以應用重載而不是模板特化。 例如

template<typename L, typename P>
L pixelToLevel(P p) {
    return static_cast<L>(p);
}

template<typename L>
L pixelToLevel(const rgb8& p) {  //       <---------- line X
    return pixelToLevel<L, uint8_t>(p.r());
}

然后pixelToLevel<uint8_t>(rgb8()); 將選擇第二個過載。

居住

@songyuanyao 的另一種解決方案是

template<typename L, typename P>
L pixelToLevel(const P& p) {
    return static_cast<L>(p);
}

暫無
暫無

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

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