c++ - 可变模板类中的模板方法

标签 c++ class templates methods variadic-templates

有什么方法可以实现这种行为吗?

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<int, int>::bar<4>()

有人可以帮助我吗?

提前致谢

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;
}

编辑3:错误

$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

最佳答案

问题在于,您从模板内调用模板方法,而没有消除模板调用语法的歧义(请参阅duplicate以获得详细说明)。

您需要此处的template 限定符:

A::template bar<N>();

关于c++ - 可变模板类中的模板方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22873493/

相关文章:

c++ - 为什么i++用在数组中

c++ - §14/2 中的 "last component"一词的含义是什么?

c++ - 在函数结束后使用指向变量的指针是否安全?

java - 自动导入哪些 Java 类/包?

java - 有没有办法制作一个可以在 Java 中使用 [] 的自定义类,类似于数组?

c++ - Ptr<Node> a = CreateObject <Node>();

HTML 电子邮件模板 Mailchimp、Outlook 和 Gmail 中的 CSS 问题

c++ - 你能从模板参数函数签名中提取类型吗

c++ - 结构对齐可能会浪费内存?

C++ 动态数组和指针