在模板类中调用模板方法 [英] Calling template methods in template classes

查看:51
本文介绍了在模板类中调用模板方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚为什么我不会编译一些代码,并且我做了相当多的减少和匿名化以结束这个例子:

I'm attempting to figure out why some code that I have won't compile and I done a fair bit of reduction an anonymizing to end up with this example:

#define NULL ((void*)0)
template<typename T>
class a {
public:
  template<bool b>
  T * amem() {
    return NULL;
  }
};

template<typename T>
class b {
public:
  a<T>* ap;

  template <bool b>
  T * m() {
    return ap->amem<b>();
  }
};

int main()
{
  return 0;
}

根据我使用的编译器和变量的名称,我会收到不同的错误.不过,它们都以这条线为中心:

Depending on the compiler that I use and the names of the variables I get different errors. They are all centered around this line, though:

    return ap->amem<b>();

使用 clang++ 编译 [Apple clang version 4.0 (tags/Apple/clang-421.0.57)(基于 LLVM 3.1svn)],我收到以下消息:

Compiling using clang++ [Apple clang version 4.0 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)], I get the following message:

tmp.cpp:18:26: error: expected expression
      return ap->amem<b>();
                         ^
1 error generated.

使用 g++ 编译 [i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1],我收到以下消息:

Compiling using g++ [i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1], I get the following message:

tmp.cpp: In member function ‘T* b<T>::m()’:
tmp.cpp:18: error: expected primary-expression before ‘>’ token
tmp.cpp:18: error: expected primary-expression before ‘)’ token

神秘地(无论如何对我来说).如果我将 amem 的名称更改为 m,我将不再从 g++ 中得到任何错误,但是我从 clang++ 中得到同样的错误.

Mysteriously (to me, anyway). If I change the name of amem to m, I no longer get any errors from g++, but I get the same error from clang++.

我确定这里有一些我不明白的地方?有谁知道 clang 和 gcc 正在寻找什么表达式?有谁知道如何解决这个问题?

I'm sure there is something here that I just don't understand? Does anyone know what expression clang and gcc are looking for? Does anyone know how to solve this problem?

如果这是一个编译器错误(似乎值得怀疑),有没有人知道任何不涉及将 amem 转换为带有 bool 参数(而不是模板)的函数的解决方法?我已经这样做了,我可以确认这可以解决这个问题,但这是在一个热循环中,并且由 b 开启的代码是一个内存分配,可能不应该在热循环中.

If this is a compiler bug (seems doubtful), does anyone know any workarounds that don't involve converting amem into a function with a bool parameter (rather than a template)? I've done this already and I can confirm that this works around the issue, but this is inside a hot loop and the code that is switched on by b is a memory allocation that probably shouldn't be in a hot loop.

推荐答案

需要添加template关键字:

return ap->template amem<b>();

请阅读哪里以及为什么我必须放置模板"和类型名称"关键字?以获得深入的解释.

Please read Where and why do I have to put the "template" and "typename" keywords? for an in-depth explanation.

这篇关于在模板类中调用模板方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆