gpt4 book ai didi

c++ - 具有 const 参数的模板未按预期分派(dispatch)

转载 作者:行者123 更新时间:2023-11-30 01:04:03 25 4
gpt4 key购买 nike

我正在尝试在 2 个不同的函数中调度我的调用。一个用于指针,另一个用于引用。但是,一旦我使用 const 限定符,模板就不会按预期进行分派(dispatch)。在我的例子中,get_pixel 不使用任何 const 限定符,因为它应该编辑给定的参数。 set_pixel 应该使用给定的参数但不要编辑它,我希望这些参数保持 const

#include <iostream>

template <typename Color>
inline int get_pixel(
Color& color)
{
return 1;
}

template <typename T>
inline int get_pixel(
T components[])
{
return 2;
}

template <typename Color>
inline int set_pixel(
const Color& color)
{
return 1;
}

template <typename T>
inline int set_pixel(
const T components[])
{
return 2;
}

template <typename Color>
inline int set_pixel_no_const(
Color& color)
{
return 1;
}

template <typename T>
inline int set_pixel_no_const(
T components[])
{
return 2;
}


int main()
{

float c;
float tab[1];

std::cout << "Get PIXEL\n";
std::cout << "Dispatch for c : " << get_pixel(c) << "\n"; // 1
std::cout << "Dispatch for &c : " << get_pixel(&c) << "\n"; // 2
std::cout << "Dispatch for tab : " << get_pixel(tab) << "\n"; // 2

std::cout << "Set PIXEL\n";
std::cout << "Dispatch for c : " << set_pixel(c) << "\n"; // 1
std::cout << "Dispatch for &c : " << set_pixel(&c) << "\n"; // 1, Should be 2
std::cout << "Dispatch for tab : " << set_pixel(tab) << "\n"; // 1, Should be 2

std::cout << "Set PIXEL NO CONST\n";
std::cout << "Dispatch for c : " << set_pixel_no_const(c) << "\n"; // 1
std::cout << "Dispatch for &c : " << set_pixel_no_const(&c) << "\n"; // 2
std::cout << "Dispatch for tab : " << set_pixel_no_const(tab) << "\n"; // 2

return 0;
}

知道为什么 const 限定符在这里是个问题吗?

最佳答案

模板推导不作为文本替换工作,而是作为一个整体在 T 上工作。

const T 中的 T 被推导出为 float* 时,您不会得到 const float*,但是 float* const

或者 const (float*),如果我们有这样的语法的话。

关于c++ - 具有 const 参数的模板未按预期分派(dispatch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50813472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com