C ++您如何“超载"?一个可以同时使用值和类型的模板? [英] C++ how do you "overload" a template to work for both value and type?
问题描述
考虑以下简单的元查询以检查积分:
Consider this simple meta query to check integral:
#include <type_traits>
template <typename T>
struct IsIntegralConstant
{
static constexpr bool value = std::is_integral_v<T>;
};
// partial specialization if type destructuring matches an integral_constant
template <typename T, auto N>
struct IsIntegralConstant<std::integral_constant<T, N>>
{
static constexpr bool value = true;
};
template <typename T> constexpr auto isIntegralConstant_v = IsIntegralConstant<T>::value;
// Now I can do queries such as:
static_assert( isIntegralConstant_v<int> );
static_assert( isIntegralConstant_v<std::integral_constant<int, 2>> );
// it'd be nice if it could work for direct values too
// static_assert( isIntegralConstant_v<2> ); ?
// let's see...
template <auto N>
struct IsIntegralConstant<std::integral_constant<decltype(N), N>>
{
static constexpr bool value = true;
};
// gcc:
//error: partial specialization of 'struct IsIntegralConstant<std::integral_constant<decltype (N), N> >' after instantiation of 'struct IsIntegralConstant<std::integral_constant<int, 2> >' [-fpermissive]
//struct IsIntegralConstant<std::integral_constant<decltype(N), N>>
// what ?
// clang says nothing, until we force instanciation:
static_assert( isIntegralConstant_v<2> );
//#1 with x86-64 clang 8.0.0
//<source>:35:38: error: template argument for template type parameter must be a type
试玩: https://godbolt.org/z/dosK7G
似乎当您的主模板在类型或值之间做出决定时,对于所有专业化而言,您都只是受其束缚.
It seems when your primary template has made a decision between type or value, then you're simply stuck with that for all specializations.
没有办法拥有更通用的东西,例如:
Is there no way to have a more generic thing such as:
template <autotypename TorV> ... ?
推荐答案
没有办法拥有更通用的东西,例如
Is there no way to have a more generic thing such as
到目前为止,任何版本的C ++都没有.而且它也不大可能改变.尽管加载了名称IsIntegralConstant
,但显然我们不会测试IsIntegralConstant_v<2>
之类的东西.模板的实用程序在通用代码中,不缺少任何内容:
None whatsoever in any version of C++ so far. And it's also unlikely to change. Despite the loaded name IsIntegralConstant
, we are obviously not going to be testing things like IsIntegralConstant_v<2>
. The utility of templates is in generic code, where nothing is lacking:
template<auto wut>
struct bar {
// static_assert(IsIntegralConstant_v<wut>);
// ill-formed, but we only really care and need
static_assert(IsIntegralConstant_v<decltype(wut)>);
};
这篇关于C ++您如何“超载"?一个可以同时使用值和类型的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!