依赖类型自动扣除

Dependent type automatic deduction

本文关键字:类型 依赖      更新时间:2023-10-16

可以做类似:

的事情
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