未指定的模板参数
Unspecified template argument
我试图使用带有多个的模板将数据传递到函数上,但只使用第一个模板参数作为过滤器。类似这样的东西:
template <typename A, typename B>
class Component {
};
template <typename A>
class Context {
public:
void add(Component<A, void *> comp) {
}
}
typedef struct Foo { int x; } Foo;
typedef struct Bar { int y; } Bar;
Context<Foo> *context = new Context<Foo>();
Component<Foo, Bar> *comp = new Component<Foo, Bar>();
context->add(comp); // error
但是编译器抱怨它无法将Component<Foo, Bar>
转换为Component<Foo, void *>
。有办法做到这一点吗?
我认为您可能需要更改"add"方法的签名:
template <typename A>
class Context
{
public:
template<class B>
void add(Component<A, B> comp)
{
}
};
然而,我不知道你问题的细节,所以这只是猜测。
我尝试使用带有多个的模板将数据传递到函数上,但只使用第一个模板参数作为过滤器。[…]但编译器抱怨无法将Component转换为Component。有办法做到这一点吗?
好吧,你的过滤器是有效的,不是吗:你的add
函数将只匹配第二个模板参数为void*
的组件,而你提供的是Bar
。你还能期待什么?如果您希望它也能处理其他"第二个参数",可以删除过滤器,为其提供一个匹配的回退函数,或者进行某种转换。
是的,在Component
:中添加一个转换副本构造函数
template<class U, class V>
Component(Component<U,V> const& other){
// ...
};
但这仍然可以通过适当的enable_if
SFINAE防护进行改进:
// <tr1/type_traits> for C++03
#include <type_traits> // for C++0x
template<class T, class U>
struct can_convert{
// std::tr1::... for C++03
static bool const value =
std::is_same<T,U>::value || std::is_convertible<T,U>::value;
};
template<class C1, class C2>
struct ice_and{
static bool const value = C1::value && C2::value;
}
// define for clarity and brevity
#define IF_CAN_CONVERT(A,B,U,V)
typename std::enable_if<ice_and<can_convert<A,U>,can_convert<B,V> > >::type* = 0
template<class U, class V>
Component(Component<U,V> const& other, IF_CAN_CONVERT(A,B,U,V)){
// ...
};
相关文章:
- 从 XML 中读取未指定结构的每个数据成员
- 为什么当函数参数未定义为常量引用时存在无限递归?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 执行参数未提供预期结果
- 用数据填充未指定大小的数组
- 访问从联合与另一个成员集复制的联合中的一个成员是否未定义或未指定?
- 双循环变量的相等条件:未指定还是未定义
- SQL Server-未找到数据源名称,也未指定默认驱动程序
- 函数参数中数组大小未指定
- 只有未指定数量的参数的函数的目的是什么?
- 为什么在 c++ 中未指定函数参数的计算顺序
- 未指定模板参数,但仍有效
- 传递 C++11 中具有未指定参数的函数
- 当基类未指定构造函数时,如何使用仅具有带参数的构造函数的类派生基类?
- 将参数定义为未指定的模板类型
- 未指定的函数参数
- OpenCV CommandLineParser未指定参数
- 使用 range-for 循环:函数调用的参数太少,未指定单个参数'a'
- 如何在GMOCK中使用未指定的参数创建返回值
- 未指定的模板参数