相关疑难解决方法(0)

为什么功能模板不能部分专用?

我知道语言规范禁止功能模板的部分特化.

我想知道为什么禁止它的理由?它们没用吗?

template<typename T, typename U> void f() {}   //allowed!
template<> void f<int, char>()            {}   //allowed!
template<typename T> void f<char, T>()    {}   //not allowed!
template<typename T> void f<T, int>()     {}   //not allowed!
Run Code Online (Sandbox Code Playgroud)

c++ language-design partial-specialization template-specialization function-templates

78
推荐指数
4
解决办法
2万
查看次数

我应该怎么做而不是功能模板的部分特化?

我想写下面的内容:

template <typename S, typename T> void foo() {
    /* code for the general case */
}

template <typename T> void foo<MySType,T>() {
    /* partially specialized code - for any kind of T, but when S is MySType */
}
Run Code Online (Sandbox Code Playgroud)

或者,在其他情况下,以下内容:

template <typename S, typename T> void bar(const S& a, const T& b) {
    /* code for the general case */
}

template <typename T> void bar<MySType,T>(const MySType& a, const T& b) {
    /* partially specialized code - for any …
Run Code Online (Sandbox Code Playgroud)

c++ templates overloading partial-specialization template-specialization

5
推荐指数
2
解决办法
174
查看次数

使用模板类的函数模板特化

可能重复:
功能模板的部分特化

我找不到任何解决方案来解决我的问题,因为如果我用我想出的关键词进行搜索会给我一些适合不同问题的解决方案.我明白这之前一定是问过,只是找不到解决办法.

假设我有一个功能模板:

template<class any> print(any value);
Run Code Online (Sandbox Code Playgroud)

我可以像这样专注它让我们说int:

template<> print<int>(int value)
{
    std::cout << value;
}
Run Code Online (Sandbox Code Playgroud)

但现在问题是,我希望它也可以使用矢量.由于矢量类是模板类,因此变得困难.

专门化这样的功能:

template<class any> print<vector<any> >(vector<any> value) {}
Run Code Online (Sandbox Code Playgroud)

将生成以下错误(MinGW g ++):

FILE: error: function template partial specialization 'print<vector<any> >' is not allowed
Run Code Online (Sandbox Code Playgroud)

请注意,功能打印只是一个示例.

我怎么解决这个问题?

c++ templates function partial-specialization specialization

4
推荐指数
1
解决办法
1341
查看次数