【发布时间】:2011-09-17 06:10:46
【问题描述】:
我有一个接受运算符对象作为参数的函数。这个操作符被视为一种回调。此运算符对象的类型是模板参数。如何为其指定默认参数?
#include <iostream>
template<class IT, class NT>
class A
{
public:
class DefaultHandler
{
public:
NT foo() { return NT(); }
};
template <class HANDLER>
void action(HANDLER h = DefaultHandler()) // This default parameter is accepted by the compiler but appears to have no effect
{
std::cout << h.foo() << std::endl;
}
};
int main()
{
A<int, double> a;
// I want this to be legal:
a.action(); // error: no matching function for call to ‘A<int, double>::action()’
//a.action(A<int, double>::DefaultHandler()); // Works
return 0;
}
【问题讨论】:
-
不幸的是,C++03 14.8.2.4/17 说:
A template type-parameter cannot be deduced from the type of a function default argument。所以需要像 iammilind's answer 这样的解决方法。 -
@Ise Wisteria,准确地回答了我的问题,以答案的形式提出,我会接受。
-
@ecatmur 问题如何与一年新的问题重复?
-
@Adam 新问题有更好的标题和更好的答案。