gpt4 book ai didi

c++ - 将其作为模板参数传递

转载 作者:行者123 更新时间:2023-11-30 02:08:21 25 4
gpt4 key购买 nike

我有两个类 test1 和 test2:

struct test1
{
int r;

test1() {}
test1(int value) : r(value) {}

test1 foo() const;
};

struct test2
{
int r;

test2() {}
test2(int value) : r(value) {}
};

template <typename t>
struct data_t
{
static const t one;
};

template <> const test1 data_t<test1>::one = test1(1);
template <> const test2 data_t<test2>::one = test2(1);

然后我创建了一个函数来做一些事情:

template <typename t, const t& value>
t do_somthing()
{ return value; };

do_something 的 Action 很简单,它返回值的拷贝,所以在 main 函数中:

int main()
{
test1 r = do_somthing<test1, data_t<test1>::one>();
}

问题发生在执行 test1::foo 时

test1 test1::foo() const
{ return do_somthing<test1, *this>(); }

编译器因错误停止:
'this' : 只能在非静态成员函数中引用

使用 *this 它变成了 test1 const& 可接受作为第二个参数,那么为什么会出现这个错误?

最佳答案

当您调用模板 方法并明确提及参数时,例如,

do_somthing<test1, data_t<test1>::one>(); //(1) ok
do_somthing<test1, *this>(); // (2) error

然后编译器期望显式参数应该是编译时常量。在您的第 (2) 种情况下,*this 无法解析为编译时间常数,因此您会收到编译器错误。

将定义更改为以下:

template <typename t>
t do_somthing(const t& value)
{ return value; };

现在当你调用 as 时,

do_somthing<test1>(*this);  // (2) ok

它应该可以工作。因为,现在 const t& 不需要是编译时常量,即使它是在编译时解析的。

关于c++ - 将其作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6997210/

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