【问题标题】:Templated method within variadically templated class [duplicate]可变模板类中的模板方法[重复]
【发布时间】:2014-05-17 09:33:42
【问题描述】:

有没有办法实现这种行为?

template < typename... Args >
class MyClass
{
public:
    typedef std::tuple < Args... > my_tuple;


    template < int n >
    static int bar () { return -5; };

};

我需要的是这个——我有可变模板MyClass,其中包含方法foo,它是由另一种类型(在我的例子中只有整数)模板化的。这甚至可能吗?我找到了类似的解决方案,但仅适用于非可变类。

但由于bar,无法编译。

编辑: 我在 gcc 4.7.2 上编译

应该运行这样的方法MyClass&lt;int, int&gt;::bar&lt;4&gt;()

谁能帮帮我?

提前致谢

EDIT2:完整代码

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <queue>
#include <set>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <map>

template < typename... Args >
class MyClass
{
public:
    typedef std::tuple < Args... > my_tuple;


    template < int n >
    static int bar () { return -5; };

};

template < class A, int N >
static void foo()
{
    A::bar < N > ();
}


int main() { 

    foo< MyClass<int, int>, 4> ();

    return 0;
}

EDIT3:错误

$g++ -Wall -std=c++11 -g -o test.out test.cpp
test.cpp: In function ‘void foo()’:
test.cpp:28:16: error: expected primary-expression before ‘)’ token
test.cpp: In instantiation of ‘void foo() [with A = MyClass<int, int>; int N = 4]’:
test.cpp:34:30:   required from here
test.cpp:28:2: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
make: *** [test] Error 1

【问题讨论】:

  • 你的意思是方法bar
  • 您的代码中没有foo。你的代码在 Clang 3.4 上编译得很好
  • 在 gcc 4.7.2 上也可以使用 -std=c++0x 编译。
  • 您遇到了什么错误?
  • 提供了完整的代码和错误,谢谢各位 :)

标签: c++ class templates methods variadic-templates


【解决方案1】:

问题是您从模板中调用模板方法,而没有将语法作为模板调用来消除歧义(请参阅duplicate 以获得很好的解释)。

您需要template 限定符:

A::template bar<N>();

【讨论】:

    猜你喜欢
    • 2016-04-12
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    相关资源
    最近更新 更多