如果T是函数,请不要将sizeof用于T.

vla*_*don 13 c++ templates function-pointers c++14

我接近跟随struct检测是否可以通过值传递类型:

template <class T>
struct should_be_passed_by_value {
    static constexpr bool value = 
        std::is_scalar<T>::value || 
        std::is_array<T>::value || 
        std::is_reference<T>::value || 
        (sizeof(T) <= sizeof(void*));
};
Run Code Online (Sandbox Code Playgroud)

问题是:当我为类C函数指针或std :: function实例化它时,编译器说:

invalid application of 'sizeof' to a function type
Run Code Online (Sandbox Code Playgroud)

(当然).

如何修改以便value包含false

Bar*_*rry 9

如何修改以使值包含false?

任何问题都可以通过额外的间接层来解决.我们已经内置了一些这些.基本上,您希望仅在T不是函数时才使用小尺寸检查.已经存在一个元函数:std::conditional.我们可以用它来推迟评估.

小的检查,我们分成它自己的元函数:

template <class T>
struct is_small
    : std::integral_constant<bool, (sizeof(T) <= sizeof(void*))>
{ };
Run Code Online (Sandbox Code Playgroud)

然后我们可以将您的条件重写为:

template <class T>
struct should_be_passed_by_value {
    static constexpr bool value = 
        std::is_scalar<T>::value || 
        std::is_array<T>::value || 
        std::is_reference<T>::value || 
        std::conditional_t<
            std::is_function<T>::value,
            std::false_type,
            is_small<T>>::value;
};
Run Code Online (Sandbox Code Playgroud)

这样,is_small<T>只有在T不是函数的情况下才会被实例化.