gpt4 book ai didi

c++ - 为什么函数模板不能部分特化?

转载 作者:IT老高 更新时间:2023-10-28 12:06:45 29 4
gpt4 key购买 nike

我知道语言规范禁止部分函数模板的特化。

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

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!

最佳答案

在 C++0x 中更改的 AFAIK。

我想这只是一个疏忽(考虑到您总是可以通过将函数放置为类的 static 成员来获得更详细的代码的部分特化效果)。

如果有,您可以查看相关的 DR(缺陷报告)。

编辑:检查这一点,我发现其他人也相信这一点,但没有人能够在标准草案中找到任何这样的支持。 This SO thread似乎表明 C++0x 不支持函数模板的部分特化

EDIT 2:只是我所说的“将函数放置为类的 static 成员”的一个示例:

#include <iostream>
using namespace std;

// 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!

void say( char const s[] ) { std::cout << s << std::endl; }

namespace detail {
template< class T, class U >
struct F {
static void impl() { say( "1. primary template" ); }
};

template<>
struct F<int, char> {
static void impl() { say( "2. <int, char> explicit specialization" ); }
};

template< class T >
struct F< char, T > {
static void impl() { say( "3. <char, T> partial specialization" ); }
};

template< class T >
struct F< T, int > {
static void impl() { say( "4. <T, int> partial specialization" ); }
};
} // namespace detail

template< class T, class U >
void f() { detail::F<T, U>::impl(); }

int main() {
f<char const*, double>(); // 1
f<int, char>(); // 2
f<char, double>(); // 3
f<double, int>(); // 4
}

关于c++ - 为什么函数模板不能部分特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5101516/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com