依赖类型自动扣除
Dependent type automatic deduction
可以做类似:
的事情template<class T, T type>
constexpr auto f(/* type used in some way... */) // -> decltype (etc. in case of C++11)
{
return std::integral_constant<T,t>{};
}
constexpr auto z = f(3); // z is deduced as an integral_constant<int,3>;
可以肯定的是使用运行时值,但是在这种情况下为3是编译时值。也许有人知道我不知道的技巧...
[编辑] constexpr auto z2 = f&lt; 3>((;//这还可以
我只想避免重复类型。
您可以在C 中使用auto
模板参数:
template <auto T>
constexpr auto f()
{
return std::integral_constant<decltype(T), T>{};
}
用法:
f<3>(); // integral_constant<int, 3>
另外,您需要以编译时友好的方式包装价值:
template <int X>
struct int_
{
using type = int;
static constexpr value = X;
};
template <typename T>
constexpr auto f(T)
{
return std::integral_constant<typename T::type, T::value>{};
}
用法:
f(int_<3>{});
以来C 11您可以声明自己的文字(我在这里使用了std::index_sequence
,并且是C 14,但您可以轻松地找到上述的C 11实现(:
#include <utility> // for std::index_sequence and std::size_t
constexpr std::size_t ipow(std::size_t base, int exp, std::size_t result = 1) {
return exp < 1 ? result : ipow(base*base, exp/2, (exp % 2) ? result*base : result);
}
constexpr std::size_t vdot(std::index_sequence<>, std::index_sequence<>) {
return 0;
}
template <std::size_t C, std::size_t... Cs, std::size_t I, std::size_t... Is>
constexpr std::size_t vdot(std::index_sequence<C, Cs...>, std::index_sequence<I, Is...>) {
return C*ipow(10, I) + vdot(std::index_sequence<Cs...>{}, std::index_sequence<Is...>{});
}
template <char... Cs>
std::integral_constant<std::size_t, vdot(std::index_sequence<static_cast<std::size_t>(Cs - '0')...>{}, std::make_index_sequence<sizeof...(Cs)>{})> operator ""_ic() {
return {};
}
int main() {
auto ic = 3_ic;
static_cast<void>(ic);
}
[live demo]
在C 11和C 中14这是不可能按照
§14.8.2.5[temp.deduct.type] 13和14
不能从非类型的类型中推导一个模板类型参数 template-argument 。[示例:
template<class T, T i> void f(double a[10][i]);
int v[10][20];
f(v); // error: argument for template-parameter T cannot be deduced
- 末尾示例]
因此,您被迫指定一种类型。例如f<int, 3>(/*...*/)
我在回答我的最后一个问题的回答
的回答中向@barry全力以赴demo
相关文章:
- 如何从C++中的依赖类型中获得它所依赖的类型
- 将依赖名称显式标记为类型名和模板的奇怪之处
- 当基类是依赖类型时,这是一个缺陷吗
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 使用 'typename' 关键字将非类型视为依赖上下文中的类型
- 为什么依赖模板类型在部分专用化中不可推导?
- 为什么即使直到最后才定义实际类型,也可以将依赖名称视为完整
- 为什么不需要在 C++20 中的依赖类型之前指定"typename"?
- 如何使用类型专用化模板方法,该类型本身就是一个模板,其中只有返回类型依赖于模板类型
- 类型依赖于可变参数模板的类
- 类型依赖模板名称
- 模板类型依赖和继承
- C++中的循环类型依赖项死锁
- c++ 中带有容器迭代器的循环类型依赖关系(GCC 失败,而 MSVC 正常)
- C++使变量类型依赖于用户输入
- 使返回类型依赖于调用源
- 如何专用化基于类型依赖类型的C++模板化类函数
- 将 POD 联合双关到基本类型:依赖于实现或符合标准
- 使用类型依赖模板名的声明
- 非类型模板参数,其类型依赖于另一个参数