【问题标题】:C++ function template argument with templated type struct woes带有模板类型结构问题的 C++ 函数模板参数
【发布时间】:2013-01-22 05:38:49
【问题描述】:

这段代码莫名其妙地无法编译:

struct sometype
{
    template <typename T>
    T* get() { return nullptr; }
};

template <typename T>
struct anothertype
{
#if 1
    template <typename T2> struct some_wrapper { typedef T2 type; };
    typedef typename some_wrapper<sometype>::type thetype;
#else
    typedef sometype thetype;
#endif
    typedef thetype* Ptr;

    Ptr m_ptr;
    T* get() { return m_ptr->get<T>(); }
};

如果我将 #if 参数更改为 0,它会以某种方式修复。有人可以对此有所了解吗?请注意,显然毫无意义的 some_wrapper 事情实际上在我的真实代码中做了一些有用的事情。

我用的是g++ 4.7.1和-fstd=gnu++11,报错如下(指向我声明anothertype&lt;T&gt;::get的那一行:

error: expected primary-expression before '>' token
error: expected primary-expression before ')' token

【问题讨论】:

  • 如果您运行通过编译器发布的代码,您会收到该错误吗?
  • @DavidRodríguez-dribeas ideone.com/N8dQoj(正是问题中的代码)

标签: c++ function templates c++11 arguments


【解决方案1】:

很难用你所有的 typedef 来判断,但我敢打赌你需要:

m_ptr->template get<T>();

【讨论】:

  • 但是……为什么? m_ptr总是 sometype*.
  • @ipc 他有#if 1 这将是真的,所以m_ptr 是一个typename some_wrapper&lt;sometype&gt;::type*,一个依赖类型
  • 依赖什么? “表达式可能依赖于类型(取决于模板参数的类型)”。 some_wrapper&lt;sometype&gt;::type*中不涉及模板参数。
  • @ipc: 不是很明显的是为什么这会有所不同...重要的原因是some_wrapper 真的是anothertype&lt;T&gt;::some_wrapper,因此任何名称都依赖于some_wrapper成为从属名称,要解析从属名称,您需要额外的 typenametemplate 关键字。 [与 typedef typename some_wrapper&lt;sometype&gt;::type thetype; 中需要 typename 的方式完全相同]
  • @ipc:我上一条评论的一个推论可能并不明显,您可以在定义之后更改嵌套类型/模板是什么:template &lt;typename T&gt; struct A { struct B {int x;}; static int size() { return sizeof(B); } }; template &lt;&gt; struct A&lt;int&gt;::B { int y[2]; }; int main() { std::cout &lt;&lt; A&lt;int&gt;::size(); };定义类模板后对A&lt;int&gt;::B 的特化可以改变已经定义的成员函数的含义。
【解决方案2】:

您应该按如下方式修复您的函数调用,添加 template 关键字:

T* get() { return m_ptr->template get<T>(); }

您可以查看this link 以获取语法说明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 2015-06-17
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多