【问题标题】:Error when using typdef template in another template class constructor在另一个模板类构造函数中使用 typedef 模板时出错
【发布时间】:2012-10-19 07:55:41
【问题描述】:

我对模板有一点问题。由于用代码更容易解​​释,这是我的问题。

我有一个接口类:

template <typename T>
class IElemValidator
{
public:
    virtual bool validate(T val) const = 0 ;
    virtual ~IElemValidator(){};
};

还有一个 typedef 结构:

template <typename T>
struct vecValidators
{
    typedef boost::ptr_vector<IElemValidator<T>> Type;
};

我可以在任何地方使用我的 typedef 结构,除了在另一个模板类的参数中,像这样:

template <typename T>
class CTestMaybe
{
public:
    CTestMaybe(vecValidators<T>::Type* a_Validators);
};

尝试编译时,出现以下错误:

Error   2   error C2061: syntax error : identifier 'Type'

当然,我可以这样做:

template <typename T>
class CTestMaybe
{
private:
    typedef boost::ptr_vector<IElemValidator<T>> vecValidator;

public:
    CTestMaybe(vecValidator* a_Validators);


};

它运行良好,但我有点失去了对我的结构类的兴趣。

那么,我做错了什么?有没有“正确”的方式来做我想做的事?

谢谢。

【问题讨论】:

标签: c++ templates


【解决方案1】:

你要加typename:

template <typename T>
class CTestMaybe
{
public:
    CTestMaybe(typename vecValidators<T>::Type* a_Validators);
};

【讨论】:

  • 哦,谢谢。我知道 typename 有一些东西,但我找不到放在哪里。
【解决方案2】:

vecValidators&lt;T&gt;::Type 类型是一个从属名称(如果我用对了术语)。这意味着您必须在此处添加一个额外的typename

CTestMaybe(typename vecValidators<T>::Type* a_Validators);

【讨论】:

    【解决方案3】:

    C++ 编译器在你的函数声明中是一个类型,但它看到 vecValidators&lt;T&gt;::Type* 并且由于 vecValidatorstemplate 它不知道 Type 是其中的一个类型,所以你必须说出来使用typename 到编译器,因此您应该将函数更改为:

    CTestMaybe(typename vecValidators<T>::Type* a_Validators);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      相关资源
      最近更新 更多