功能对象作为模板参数
问题描述:
template <typename elemType, typename Comp = less<elemType> >
class LessThanPred {
public:
LessThanPred(const elemType &val) : _val(val){}
bool operator()(const elemType &val) const
{ return Comp(val, _val); }
void val(const elemType &newval) { _val = newval; }
elemType val() const { return _val; }
private:
elemType _val;};
这是Essential C++的一个例子。 Comp
显然是一个函数对象类的名字。为什么我可以直接使用Comp(val, _val)
?通常我想我应该先定义一个这样的函数对象:Comp comp
,然后调用comp
而不是Comp
。功能对象作为模板参数
答
由于模板成员在实例化时仅检查语义正确性,因此编译代码。尽管如此,代码在语法上格式良好。但是,当您尝试实例化LessThanPred<T>
函数调用运算符时,您将收到编译器错误。例如,随着clang
(3.6.1)的版本,我用我得到
less-than.cpp:8:18: error: no matching constructor for initialization of 'std::less<int>'
{ return Comp(val, _val); }
^ ~~~~~~~~~
less-than.cpp:17:25: note: in instantiation of member function 'LessThanPred<int, std::less<int> >::operator()' requested here
LessThanPred<int>(2)(1);
试图使用功能
LessThanPred<int>(2)(1)
+0
对于默认情况下,我可以更改代码'{返回Comp(val,_val); }'到{return Comp()(val,_val); }? – yycfox
+0
@yycfox:是的,创建一个实例应该可以做到。 –
比较时,一个类型参数,而不是一个函数对象类名称。顺便说一句,你实际上可以定义一个Comp Comp对象,然后调用comp。 – user2296177
您是否实例化/使用'LessThanPred'的函数调用操作符?由于它是模板成员,因此只有在实例化时才能正确检查。 –
由于引用不正确,我正在投票结束此题,因为引用不正确 –