【发布时间】:2013-04-20 21:46:39
【问题描述】:
我已经为此苦苦挣扎了大约半天,似乎至少 XCode 4.6 有一个错误,即模板类的某些声明会违反语言并允许将 const 数据从类内传递到带参数的外部函数没有 const 修饰符。
下面的示例将编译,即使是艰难的模板声明 Tcaller::call() 方法指定作为引用传递的 const 参数 但是静态 cmp 函数提供了无用的 *const & 修饰符。
template< typename T> struct Tcalled
{
// !!!error - this prototype doesn't protect the data passed to function
// because it should be declared with const modifiers but it wouldn't compile then.
// SEE: Below my NOTE for correct function prototype.
static bool cmp(const Tcalled*& item, const int& key) //<- correct but doesn't work
static bool cmp(Tcalled* const & item, const int& key) //<- invalid but works!!
{
return (item->index = key); /// error - we modify const object here !
}
T index;
};
template < typename T> struct Tcaller
{
Tcaller(){}
template < typename K, bool (*compare)(const T& item, const K& key) >
bool call(int k) const { return compare(data, k); }
T data;
};
int main(int argc, char *argv[])
{
const Tcaller<Tcalled<int>* > tmp; // <- const data
int k = 1;
tmp.call<int,Tcalled<int>::cmp>(k); //call here WILL modify const data !!
}
还有一个问题:我如何强制 XCode 遵守规则并允许我进行原型设计 我为模板参数声明的静态函数?至于现在,这些是我在正确声明静态方法时得到的 XCode 错误:
调用“call”没有匹配的成员函数 候选模板被忽略:模板参数“比较”的显式指定参数无效
谢谢!
【问题讨论】:
-
const Tcalled*是指向 const Tcall 的指针,Tcalled* const是指向 Tcall 的 const 指针。它们是不同的东西
标签: c++ xcode templates pointers arguments