C++ 将此作为模板参数传递
我有两个类test1和test2:C++ 将此作为模板参数传递,c++,templates,C++,Templates,我有两个类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
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的操作非常简单,它返回一个值的副本,因此在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&它可以作为第二个参数接受,那么为什么会出现这个错误呢?编译器会确切地告诉您为什么这不起作用,“this”:只能在非静态成员函数中引用。它在任何其他上下文中都不可用 如果要以这种方式模板化此函数,则必须使用能够在编译时推断参数类型的模板函数,如下所示:
template <class T>
T copy_value(const T& value)
{
return value;
}
class A
{
public:
A clone()
{
return copy_value(*this);
}
};
int main()
{
int x = 999;
int y = copy_value(x);
double d = 9.99;
double e = copy_value(d);
std::string s = "Test";
std::string t = copy_value(s);
return 0;
}
在上面的每个例子中,函数模板都是在编译时推导出来的,因此编译器可以正确地生成所需的代码。与此模板一起使用的类应具有适当的可复制性和可复制性。编译器会确切地告诉您为什么这不起作用,“this”:只能在非静态成员函数中引用。它在任何其他上下文中都不可用 如果要以这种方式模板化此函数,则必须使用能够在编译时推断参数类型的模板函数,如下所示:
template <class T>
T copy_value(const T& value)
{
return value;
}
class A
{
public:
A clone()
{
return copy_value(*this);
}
};
int main()
{
int x = 999;
int y = copy_value(x);
double d = 9.99;
double e = copy_value(d);
std::string s = "Test";
std::string t = copy_value(s);
return 0;
}
在上面的每个例子中,函数模板都是在编译时推导出来的,因此编译器可以正确地生成所需的代码。与此模板一起使用的类应具有适当的可复制性和可复制性。当调用模板方法并明确提及以下参数时
do_somthing<test1, data_t<test1>::one>(); //(1) ok
do_somthing<test1, *this>(); // (2) error
现在当你打电话给
do_somthing<test1>(*this); // (2) ok
它应该会起作用。因为,现在const t&不需要是编译时常量,即使它是在编译时解析的。当您调用一个模板方法并显式地提到如下参数时
do_somthing<test1, data_t<test1>::one>(); //(1) ok
do_somthing<test1, *this>(); // (2) error
现在当你打电话给
do_somthing<test1>(*this); // (2) ok
它应该会起作用。因为,现在const t&不需要是编译时常量,即使它是在编译时解析的