gpt4 book ai didi

c++ - 如何为多种 C++ 类型创建编译时检查?

转载 作者:搜寻专家 更新时间:2023-10-31 00:51:37 26 4
gpt4 key购买 nike

我有一个 template <class Class>通用功能,包括:

std::ostringsteam objectStream;

objectStream << std::forward<Class>(object);

return objectStream.str();

为了效率,我想优化Class的情况字符串。

因此,我在模板上执行标记分派(dispatch)以重载模板函数,每个项目 27 是 Scott Myers 的 Effective Modern C++ 书。

因此我需要在编译时生成 std::true_typestd::false_type .

给定一个 template<class Class> , 我需要一个 std::true_type如果这些表达式中的任何一个为真:

std::is_same<typename std::decay<Class>::type,       char   * >()
std::is_same<typename std::decay<Class>::type, const char * >()
std::is_same<typename std::decay<Class>::type, string >()
std::is_same<typename std::decay<Class>::type, string * >()
std::is_same<typename std::decay<Class>::type, const string * >()

我不确定如何执行 OR 以便编译器可以在编译时正确地分派(dispatch)标签。

相关问题,有没有办法删除constconst char *让它成为char *

最佳答案

对于你的第一个问题,

如果您使用的是 c++17,则可以使用折叠表达式在几行中完成此操作

#include <iostream>
using namespace std;

template <typename C, typename... Ts>
using matches_my_types = std::bool_constant< ( ... | std::is_same<C,Ts>::value)>;

//or with a predefined set of types..
template <typename C>
using matches_my_predefined_set_of_types = matches_my_types<C,bool,double,int>;

int main() {

using Class = int;
std::cout << matches_my_types<Class,bool,double,int>::value << std::endl;
std::cout << matches_my_predefined_set_of_types<Class>::value << std::endl;
return 0;
}

Demo

对于 c++11,您可以做类似的事情,但使用递归代替折叠。

#include <iostream>
using namespace std;

template<typename B, typename...Bs> struct any_true
: std::conditional_t<bool(B::value), B, any_true<Bs...>>{};
template<typename B> struct any_true<B> : B {};

template <typename C, typename... Ts>
using matches_my_types = any_true<std::is_same<C,Ts>...>;


int main() {

using Class = int;
std::cout << matches_my_types<Class,bool,double,int>::value << std::endl;
return 0;
}

Demo

对于你的第二个问题,如果你想在指向 const T 的指针上删除 const,你可以使用内置的 type_traits 和条件,

#include <iostream>
#include <typeinfo>

using namespace std;

template <typename T>
using remove_const_if_pointer_to_const =
std::conditional_t<std::is_pointer<T>::value,
std::add_pointer_t<std::remove_const_t<std::remove_pointer_t<T>>>,
T>;

int main() {

using A = int;
using B = int*;
using C = const int*;

std::cout << typeid(remove_const_if_pointer_to_const<A>).name() << std::endl;
std::cout << typeid(remove_const_if_pointer_to_const<B>).name() << std::endl;
std::cout << typeid(remove_const_if_pointer_to_const<C>).name() << std::endl;

return 0;
}

Demo

关于c++ - 如何为多种 C++ 类型创建编译时检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54562138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com