【问题标题】:C++: forward a template member function call failed [duplicate]C ++:转发模板成员函数调用失败[重复]
【发布时间】:2015-03-07 13:32:43
【问题描述】:

假设我有一个模板类TemplateClass,模板函数templFcn如下:

template <typename T>
struct TemplateClass {
  template <bool Bool> void templFcn(int i) { }
};
void test() {
  TemplateClass<float> v;
  v.templFcn<true>(0);  // Compiles ok.
}

现在我想写一个forward 函数来模拟这种行为

template <typename T, template<typename> class C, bool Bool>
void forward(C<T>& v) {
  v.templFcn<Bool>(0);  // Compiler error, Line 16 (see below)
};

void test2() {
  TemplateClass<float> v;
  forward<float,TemplateClass,true>(v);  // Line 21
}

clang++编译错误:

test.cc:16:5: error: reference to non-static member function must be called
  v.templFcn<Bool>(0);
  ~~^~~~~~~~
test.cc:21:3: note: in instantiation of function template specialization
      'forward<float, TemplateClass, true>' requested here
  forward<float,TemplateClass,true>(v);
  ^
test.cc:3:29: note: possible target for call
  template <bool Bool> void templFcn(int i) { }
                        ^
1 error generated.

有人可以解释为什么这种模板转发在这种情况下会失败吗?有没有办法规避它?谢谢!

【问题讨论】:

    标签: c++ templates c++11 template-meta-programming


    【解决方案1】:
    v.template templFcn<Bool>(0); // Compiler error, Line 16 (see below)
    

    从属子句需要消歧,所以它知道&lt;是一个模板子句开头,而不是小于。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多