嵌套模板C++

vku*_*cki 6 c++ templates metaprogramming

我有一个表单的模板类:

template<typename ContainerType>
class ConfIntParamStat {
  public:
    typedef typename ContainerType::Type Type;
...
  private:
    void sample(int iteration) {...}
}
Run Code Online (Sandbox Code Playgroud)

我想为ContainerType是Vector的情况创建一个特定版本的函数示例.Vector本身是一个模板类,但我不知道这个Vector包含哪种类型的值.

我的直觉是在头文件中创建它:

template<typename Type>
ConfIntParamStat<Vector<Type> >::sample(int iteration) {
...
}
Run Code Online (Sandbox Code Playgroud)

但是它没有编译,而clang的错误是:

error: nested name specifier 'ConfIntParamStat<Vector<Type> >::' for declaration does not refer into a class, class template or class template partial specialization
Run Code Online (Sandbox Code Playgroud)

是否可以使用其他语法?

Cur*_*ous 2

如果您不想专门化模板并正在寻找仅限会员的专门化,请尝试以下操作

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

template <typename ContainerType>
class Something {
  public:

    void do_something(int);

    template <typename Which>
    struct do_something_implementation {
        void operator()() {
            cout << "general implementation" << endl;
        }
    };
    template <typename Which>
    struct do_something_implementation<vector<Which>> {
        void operator()() {
            cout << "specialized implementation for vectors" << endl;
        }
    };
};

template <typename ContainerType>
void Something<ContainerType>::do_something(int) {
    do_something_implementation<ContainerType>{}();
}

int main() {
    Something<double> something;
    something.do_something(1);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您的目的是专门化一个函数,我会像这样重载该函数

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

template <typename ContainerType>
class Something {
  public:

    void do_something(int);

    template <typename Type>
    void do_something(const vector<Type>&);
};

template <typename ContainerType>
void Something<ContainerType>::do_something(int) {
    cout << "Called the general method for do_something" << endl;
}

template <typename ContainerType>
template <typename Type>
void Something<ContainerType>::do_something(const vector<Type>&) {
    cout << "Called the specialised method" << endl;
}

int main() {
    vector<int> vec{1, 2, 3};
    Something<double> something;
    something.do_something(1);
    something.do_something(vec);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这就是不需要完整/显式函数模板专业化的主要原因。重载可以实现几乎相同的效果!

注意这是一篇与您的问题相关的很棒的文章!http://www.gotw.ca/publications/mill17.htm