Kno*_*abe 1 c++ template-meta-programming c++11
我一直在玩标签调度,以下代码完全符合我的预期:
#include <type_traits>
#include <iostream>
void impl(std::true_type) { std::cout << "true\n"; }
void impl(std::false_type) { std::cout << "false\n"; }
template<typename T>
void dispatch(T&& val)
{
impl(std::is_integral<typename std::remove_reference<T>::type>());
}
int main()
{
dispatch(10); // calls impl(std::true_type)
dispatch(""); // calls impl(std::false_type)
}
Run Code Online (Sandbox Code Playgroud)
但如果我想否定这个条件,我就会遇到麻烦.我想我可能只是抛出一个" !"到里面的代码dispatch,
impl(!std::is_integral<T>()); // added "!"
Run Code Online (Sandbox Code Playgroud)
但这不会编译.
我需要做些什么才能使此代码生效?
你可以std::integral_constant从constexpr值中实例化一个这样的:
impl(std::integral_constant<bool, !std::is_integral<T>::value>());
Run Code Online (Sandbox Code Playgroud)
std::true_type而std::false_type实际上别名此类.另一种方法是为此引入一个元函数:
template <typename T>
struct not_ : std::integral_constant<bool, !T::value> {};
Run Code Online (Sandbox Code Playgroud)
并使用(调用)它:
impl(typename not_<std::is_integral<T>>::type());
Run Code Online (Sandbox Code Playgroud)
或使用类似的 boost::mpl
你可以实现operator !的std::integral_constant(潜在的类型true_type和false_type):
template <typename T, T value>
inline constexpr std::integral_constant<T, !value>
operator ! (std::integral_constant<T, value>)
{ return {}; }
Run Code Online (Sandbox Code Playgroud)
这似乎是可以轻松标准化的便利小事之一.