首页 > 解决方案 > 带有 const ref 参数的函数模板特化

问题描述

以下代码编译良好

#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 pconst rgb8& p,则编译失败。

(生成的确切编译器错误取决于显式模板参数rgb8是否也更改为const rgb8&。)

如果我想p通过引用而不是 X 行的值传递,如何编译它?

标签: c++templatesc++14template-specializationfunction-templates

解决方案


@songyuanyao 的另一种解决方案是

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

推荐阅读