3

假设我们有这样的元函数:

template<typename LHS , typename RHS>
struct add;

我们有一组已知类型的特化。例如,完整的包装器:

template<typename T1 , T1 VALUE1 , typename T2 , T2 VALUE2>
struct add<std::integral_constant<T1,VALUE1>,std::integral_constant<T2,VALUE2> : public std::integral_constant<std::common_type_t<T1,T2>,VALUE1+VALUE2> {}; //Take advantage of C++14 helpers

前几天,我们新建了一个类,专门为这个类添加:

template<typename X , typename Y>
struct point_2d
{
    using x = X;
    using y = Y;
};

template<typename X1 , typename Y1 , typename X2 , typename Y2>
struct add<point_2d<X1,Y1>,ppoint_2d<X2,Y2>> : public point_2d<add<X1,X2>,add<Y1,Y2>> {};

如您所见,我使用add元函数来执行坐标的添加。因此,任何具有 add 元功能专业化的类型都可以用作point_2d坐标。

我的问题是:有什么方法可以检查模板是否具有以给定类型作为参数的专业化?

像这样的东西:

template<template<typename...> class TEMPLATE , typename... Ts>
struct has_specialization;

template<template<typename...> class TEMPLATE , typename... Ts>
struct has_specialization<TEMPLATE<Ts...> /* TEMPLATE<Ts...> exists */ , Ts...> : public std::true_type {};

template<template<typename...> class TEMPLATE , typename... Ts>
struct has_specialization<TEMPLATE<Ts...> /* TEMPLATE<Ts...> doesn't exists */ , Ts...> : public std::false_type {};
4

1 回答 1

7

@BartekBanachewicz 的想法是通过断言提供用户友好的编译器错误。如果我可以检查(按照 point_2d 示例)传递的坐标是否可添加(也就是说,是否为该坐标定义了 add 元函数的专门化),我可以提供更多可读错误,例如“该坐标不可添加。point_2d需要可添加的坐标来添加点”,而不是常见的可怕的模板实例化错误。

鉴于这是您提出问题的动机,这不是一个更简单、更直接的解决方案:

#include <type_traits>

template<typename LHS , typename RHS>
using cannot_add =  std::integral_constant<bool,std::is_same<LHS,LHS>::value>;

template<typename LHS , typename RHS>
struct add
{
    /* Assert some expressively named condition that is always false 
        but is dependent on a template parameter.
    */
    static_assert(!cannot_add<LHS,RHS>::value,
        "Types are not addable. Need specialization");
};

template<typename T1 , T1 VALUE1 , typename T2 , T2 VALUE2>
struct add<std::integral_constant<T1,VALUE1>,std::integral_constant<T2,VALUE2>> 
: public std::integral_constant<
    typename std::common_type<T1,T2>::type,
    VALUE1+VALUE2
> {};  

int main()
{
    add<std::integral_constant<int,1>,std::integral_constant<int,2>> x; // Line 25 
    add<float,float> y; // Line 26
    return 0;
}

GCC 4.8.1 诊断:

main.cpp:26:19:   required from here
main.cpp:12:2: error: static assertion failed: Types are not addable. Need specialization

Clang 3.3 诊断:

main.cpp:12:2: error: static_assert failed "Types are not addable. Need specialization"
    static_assert(!cannot_add<LHS,RHS>::value,
    ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:26:19: note: in instantiation of template class 'add<float, float>' requested here
    add<float,float> y; // Line 26
                 ^
于 2013-07-29T06:48:56.343 回答