部分专业化和嵌套模板
partial specialisation and nested templates
我试图对一个模板函数进行部分专门化,其中专门化类型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() };
}
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- C++-模板嵌套类的引用初始化无效
- 嵌套模板类的模板类模板模板参数的专业化
- 嵌套模板类声明后的嵌套模板类专业化