[英]const reference to a function in a template parameter?
如何聲明要使用const函數引用(在模板參數中)? 例如,
template< bool (&func)(int arg) >
void foo(int stuff);
但是const?
更具體地說,如果我嘗試使用icpc
編譯以下內容:
template<bool (&func)(int arg)>
bool id(int arg) {
return func(arg);
}
class Foo {
public:
Foo() {};
virtual ~Foo() {};
bool bar(int arg) { return true; }
bool bar2(int arg) {
return id<bar>(arg);
};
};
int main() {
return 0;
}
我懂了
$ icpc foo.cpp
foo.cpp(12): error: no instance of function template "id" matches the argument list
argument types are: (int)
return id<bar>(arg);
^
compilation aborted for foo.cpp (code 2)
或者,使用g++
,我得到
$ g++ foo.cpp
foo.cpp: In member function ‘bool Foo::bar2(int)’:
foo.cpp:13:23: error: no matching function for call to ‘id(int&)’
return id<bar>(arg);
^
foo.cpp:13:23: note: candidate is:
foo.cpp:2:6: note: template<bool (& func)(int)> bool id(int)
bool id(int arg) {
^
foo.cpp:2:6: note: template argument deduction/substitution failed:
foo.cpp:13:23: error: could not convert template argument ‘Foo::bar’ to ‘bool (&)(int)’
return id<bar>(arg);
^
但是,如果我改為將欄移到頂層,例如
template<bool (&func)(int arg)>
bool id(int arg) {
return func(arg);
}
bool bar(int arg) { return true; }
class Foo {
public:
Foo() {};
virtual ~Foo() {};
bool bar2(int arg) {
return id<bar>(arg);
};
};
int main() {
return 0;
}
它編譯良好。 為什么會發生這種情況?如何在不將bar設置為全局的情況下解決該問題?
注意:在我的原始代碼中,我得到“(不能用類型值初始化)(錯誤)”錯誤:(使用icpc
)
CollisionWorld.cpp(73): error: a reference of type "bool (&)(const Line &, vec_dimension={double}, vec_dimension={double}, vec_dimension={double}, vec_dimension={double})" (not const-qualified) cannot be initialized with a value of type "bool (const Line &, vec_dimension={double}, vec_dimension={double}, vec_dimension={double}, vec_dimension={double})"
QuadTree<Line, vec_dimension, line_inside_box_with_time> *quad_tree =
^
(使用g++
)
CollisionWorld.cpp:73:58: error: could not convert template argument ‘CollisionWorld::line_inside_box_with_time’ to ‘bool (&)(const Line&, double, double, double, double)’
QuadTree<Line, vec_dimension, line_inside_box_with_time> *quad_tree =
^
問題在於模板需要自由功能,而不是成員功能。 這就是為什么當您將bar()放到Foo中時它起作用的原因,
像這樣嘗試:
template<typename C, bool (C::*func)(int arg)>
bool id(C *mthis, int arg) {
return (mthis->*func)(arg);
}
class Foo {
public:
Foo() {};
virtual ~Foo() {};
bool bar(int arg) { return true; }
bool bar2(int arg) {
return id<Foo, &Foo::bar>(this, arg);
};
};
要調用成員函數,您需要做兩件事: this
指針和函數。 因此,不可能像編寫它那樣容易。 id
將需要this
指針!
模板定義如下所示:
template<bool (Foo::*func)(int)>
但是,您仍然不能實現同時在函數和成員函數上起作用的true id
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.