部分专业化和嵌套模板

partial specialisation and nested templates

本文关键字:嵌套 专业化      更新时间:2023-10-16

我试图对一个模板函数进行部分专门化,其中专门化类型T也可能是类模板。但是,以下代码不起作用。

#include <iostream>
#include <vector>
template <class T>
constexpr T neutral();
template <>
constexpr int neutral() { return 0; } // Okay. This is how partial specialisation works.
template <class U>
constexpr std::vector<U> neutral() { return std::vector<U>{ neutral<U>() }; }
int main()
{
const auto n{ neutral<std::vector<int>>() }; // error
}

main.cpp:16:19: error: call to 'neutral' is ambiguous
const auto n{ neutral<std::vector<int>>() }; // error
^~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:5:13: note: candidate function [with T = std::vector<int, std::allocator<int> >]
constexpr T neutral();
^
main.cpp:11:26: note: candidate function [with U = std::vector<int, std::allocator<int> >]
constexpr std::vector<U> neutral() { return std::vector<U>{ neutral<U>() }; } //error
^

我的设计目标如下:我提供了一种算法,可以采用任何程序员想要使用的任何类型,只要他定义了T类型的所谓natural<T>()是什么

如何正确实施?

我首先想到,它一定是类似的东西

template <>
template <class U>
constexpr std::vector<U> neutral<std::vector<U>>() { return std::vector<U>{ neutral<U>() }; } //error

但这也会导致错误:

main.cpp:11:26: error: function template partial specialization is not allowed
constexpr std::vector<U> neutral<std::vector<U>>() { return std::vector<U>{ neutral<U>() }; } //error
^      ~~~~~~~~~~~~~~~~

编辑:我想使用的上下文如下。。。

我有一个类class Z7,它代表一个(数学(环。我想在这个例子中使用类似neutral的东西来表示环的零和一元素。然后有一个类

template <class _Ring>
class polynomial;

其将表示环_Ring上的多原子,例如2x^5 + x^3 + 4x + 1。因此,每当_Ring已经是环时,polynomial<_Ring>也将是环。因此,我想通过使用类型为_Ring的零和一,为polynomial<_Ring>定义一个零和一的模板专门化。

函数需要在参数上有所不同才能有不同的定义,类/结构可以在没有这种约束的情况下进行专门化,也许你想要的更接近…

#include <vector>
template <typename T>
struct neutral;
template <typename T>
struct neutral {
static constexpr int get() { return 0; } 
};
template <typename T>
struct neutral<std::vector<T>> {
static constexpr std::vector<T> get() { return std::vector<T>(); } 
};
int main()
{
const auto n{ neutral<std::vector<int>>::get() };
const auto m{ neutral<float>::get() };
}