调用模板类的模板成员函数时出现错误的编译错误 我有一个模板C++类,它的成员函数中有一个模板。
在我的代码中,我在两个地方调用它,其中一个有效,另一个产生了一个非常混乱的错误,可以归结为下面的示例代码:调用模板类的模板成员函数时出现错误的编译错误 我有一个模板C++类,它的成员函数中有一个模板。,c++,templates,gcc,C++,Templates,Gcc,在我的代码中,我在两个地方调用它,其中一个有效,另一个产生了一个非常混乱的错误,可以归结为下面的示例代码: #include <memory> template <unsigned char N> struct Foo { template <typename OtherFoo, unsigned X> void do_work ( const OtherFoo * __restrict, float,
#include <memory>
template <unsigned char N>
struct Foo
{
template <typename OtherFoo, unsigned X>
void do_work (
const OtherFoo * __restrict,
float,
Foo * __restrict
)
const
{
}
};
struct Bar
{
std :: unique_ptr <Foo<0>> foo_0;
std :: unique_ptr <Foo<1>> foo_1;
std :: unique_ptr <Foo<2>> foo_2;
void run (float);
template <typename FOO>
void run (std :: unique_ptr <FOO> & foo, float x)
{
FOO out;
foo -> template do_work <123> (foo_2.get(), x, &out);
}
};
void Bar :: run (float x)
{
if (foo_0)
run (foo_0, x);
else
run (foo_1, x);
}
int main ()
{
Bar bar;
bar .run (1.23);
}
#包括
模板
结构Foo
{
模板
你干什么(
const OtherFoo*\u restrict,
浮动
Foo*\u限制
)
常数
{
}
};
结构条
{
std::unique_ptr foo_0;
std::唯一的_ptr foo_1;
std::唯一的\u ptr foo_2;
无效运行(浮动);
模板
无效运行(标准::唯一\u ptr&foo,浮动x)
{
富出;
foo->template do_work(foo_2.get(),x,&out);
}
};
空栏::运行(浮动x)
{
如果(foo_0)
运行(foo_0,x);
其他的
运行(foo_1,x);
}
int main()
{
酒吧;
bar.run(1.23);
}
错误消息非常简单,但显然是错误的
temp.cpp: In member function ‘void Bar::run(std::unique_ptr<FOO>&, float) [with FOO = Foo<0u>]’:
temp.cpp:61:16: instantiated from here
temp.cpp:54:3: error: no matching function for call to ‘Foo<0u>::do_work(Foo<2u>*, float&, Foo<0u>*)’
temp.cpp: In member function ‘void Bar::run(std::unique_ptr<FOO>&, float) [with FOO = Foo<1u>]’:
temp.cpp:63:16: instantiated from here
temp.cpp:54:3: error: no matching function for call to ‘Foo<1u>::do_work(Foo<2u>*, float&, Foo<1u>*)’
temp.cpp:在成员函数“void Bar::run(std::unique_ptr&,float)[with FOO=FOO]中:
临时cpp:61:16:从此处实例化
临时cpp:54:3:错误:调用“Foo::do_work(Foo*,float&,Foo*)”时没有匹配的函数
temp.cpp:在成员函数“void Bar::run(std::unique_ptr&,float)[with FOO=FOO]]中:
临时cpp:63:16:从此处实例化
临时cpp:54:3:错误:调用“Foo::do_work(Foo*,float&,Foo*)”时没有匹配的函数
让我们看看,没有匹配的函数用于调用Foo::do_work(Foo*,float&,Foo*)
。。。?不,在我看来,就像Foo::do_work的一个有效实例
编译器错了吗?(Ubuntu12.04上的gcc 4.5.1)特别奇怪的是,这段代码在代码的其他地方编译时似乎是一个等价的调用(完整的东西有太多的依赖项,无法在这里有意义地复制)。您应该更改
do_work()
函数模板的模板参数顺序,否则,您的实例化将确实不正确:
// template<typename OtherFoo, unsigned X> // This order is not appropriate.
// Let template parameters that
// cannot be deduced come first...
template<unsigned X, typename OtherFoo>
// ^^^^^^^^^^ ^^^^^^^^^^^^^^^^^
// THIS FIRST THEN THIS
void do_work(const OtherFoo* __restrict, float, Foo* __restrict) const
{
}
//模板//此顺序不合适。
//让模板参数
//无法推断先来。。。
模板
// ^^^^^^^^^^ ^^^^^^^^^^^^^^^^^
//先这个然后这个
void do_work(const OtherFoo*\uuu restrict,float,Foo*\uu restrict)const
{
}
这是因为在以下函数调用中,您为第一个模板参数提供了一个显式参数:
foo->template do_work<123>(foo_2.get(), x, &out);
foo->template do_work(foo_2.get(),x,&out);
试试gcc 4.7,它会给你一个更详细的错误消息。\u restrict
不是一个标识符,它是一个类型限定符。@Xymostech:哦,很抱歉。我早该想到的。修好了,谢谢。