未指定的模板参数

Unspecified template argument

本文关键字:参数 未指定      更新时间:2023-10-16

我试图使用带有多个的模板将数据传递到函数上,但只使用第一个模板参数作为过滤器。类似这样的东西:

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)){
  // ...
};