如何解决功能模板的局部特化?

use*_*020 10 c++ templates template-specialization

例如,我有一个班级:

class A
{
    enum {N = 5};
    double mVariable;

    template<class T, int i>
    void f(T& t)
    {
        g(mVariable); // call some function using mVariable.
        f<T, i+1>(t); // go to next loop
    }

    template<class T>
    void f<T, N>(T& t)
    {} // stop loop when hit N.
};
Run Code Online (Sandbox Code Playgroud)

功能模板中不允许部分特化.在我的情况下,我该如何解决这个问题?

我略微改变了Arne Mertz的例子,如:

template<int n>
struct A
{
    enum {N = n};
    ...
};
Run Code Online (Sandbox Code Playgroud)

并使用A像:

A<5> a;
Run Code Online (Sandbox Code Playgroud)

我无法在Visual Studio 2012上编译.它是编译器错误还是其他什么?这很奇怪.

编辑:检查.这是一个Visual Studio错误.:(

我认为Nim提供了实现它的最简单方法.

Arn*_*rtz 7

最直接的解决方案是使用模板类而不是函数:

class A
{
    enum {N = 5};
    double mVariable;

    template <class T, int i>
    struct fImpl {
      static_assert(i<N, "i must be equal to or less than N!");
      static void call(T& t, A& a) {
        g(a.mVariable);
        fImpl<T, i+1>::call(t, a);
      }
    };

    template<class T>
    struct fImpl<T,N> {
      static void call(T&, A&)  {} // stop loop when hit N.
    };

 public:

    template<class T, int i>
    void f(T& t)
    {
        fImpl<T, i>::call(t,*this);
    }

};
Run Code Online (Sandbox Code Playgroud)

示例链接

  • +1,但只是一个挑剔:如果`A`本身就是一个类模板,人们可能会遇到专门嵌套模板的困难(取决于部分vs完全特化).因此,在这种情况下,最好将这些内容移动到`detail`命名空间中. (2认同)

Nim*_*Nim 2

借助 c++11 支持,您可以执行以下操作:

#include <iostream>
#include <type_traits>
using namespace std;

struct A
{
    enum {N = 5};
    double mVariable;

    void g(int i, double v)
    { std::cout << i << "  " << v << std::endl; }

    template<int i, class T>
    typename enable_if<i >= N>::type f(T& t)
    {} // stop loop when hit N.

    template<int i, class T>
    typename enable_if<i < N>::type f(T& t)
    {
        g(i, mVariable); // call some function using mVariable.
        f<i+1, T>(t); // go to next loop
    }

};

int main(void)
{
    A a;
    int v = 0;
    a.f<0>(v);
}
Run Code Online (Sandbox Code Playgroud)

我喜欢的主要原因是你不需要之前答案所要求的任何废话......