比方说,我有六种类型,它们各自属于一个概念类别.
这是一个显示这个的图表:

或者也许是一个更具体的例子:

我想编写两个函数来处理所有6种类型.
"类别1"中的类型以某种方式处理,"类别2"中的类型以不同的方式处理.
让我们进入代码.首先,我将创建六种类型.
//Category 1 Types
class Type_A{};
class Type_B{};
class Type_C{};
//Category 2 Types
class Type_D{};
class Type_E{};
class Type_F{};
Run Code Online (Sandbox Code Playgroud)
接下来,我将创建两个类型特征,以便可以在编译时发现类型的类别.
/* Build The Category 1 Type Trait */
//Type_A Type Trait
template <typename T>
struct Is_Type_A {
static const bool value = false;
};
template <>
struct Is_Type_A<Type_A> {
static const bool value = true;
};
//Type_B Type Trait
template <typename T>
struct Is_Type_B {
static const bool value = false;
};
template <>
struct …Run Code Online (Sandbox Code Playgroud) 在求职面试中,我被要求编写一个确定某个类型是否为指针的元函数.这是我提出的:
template <typename T>
struct is_pointer
{ static const bool value = false; }
template <typename T>
struct is_pointer<T *>
{ static const bool value = true; }
Run Code Online (Sandbox Code Playgroud)
然后我被要求编写一个元断言,如果我的is_pointer函数没有做正确的事情,它将在编译期间失败.
当我使用时static_assert,他明确地告诉我,我可能只使用C++ 98标准.我怎样才能做到这一点?
我昨天问了一个关于模板方法重载和使用类型特征解决问题的问题。我收到了一些很好的答案,他们引导我找到了解决方案。这个解决方案让我进行了更多阅读。
我登陆了 Fluent CPP 的一个页面——https ://www.fluentcpp.com/2018/05/18/make-sfinae-pretty-2-hidden-beauty-sfinae/,这个页面很有趣,然后我听了博卡拉先生引用了斯蒂芬·杜赫斯特的讲话。这一切都令人着迷。
我现在正试图多了解一点。在昨天的答案中,我得到了这个解决方案:
template< class Function, class... Args,
std::enable_if_t<std::is_invocable_v<Function, Args...>, std::nullptr_t> = nullptr>
explicit MyClass( const std::string & theName, Function&& f, Args&&... args )
: name(theName)
{
runner(f, args...);
}
Run Code Online (Sandbox Code Playgroud)
在阅读了 CPP Fluent 帖子并观看了演讲之后,我得出了最终的解决方案:
template< class Function, class... Args>
using IsInvocable = std::enable_if_t < std::is_invocable_v<Function, Args...> >;
template< class Function, class... Args, typename = IsInvocable<Function, Args...> >
explicit ThreadHandle( const std::string & name, Function && f, Args &&... args ) {
startWithName(name, f, …Run Code Online (Sandbox Code Playgroud) 用什么来替代C++中的概念(即将推出的特性)?
您可能听说过C++中的概念.该功能允许您指定模板中类型的要求.
我正在寻找一种方法来实现这一点,我找到的最好的是在Stroustrup的书中,他将谓词与static_assert一起使用,如下所示:
template<typename Iter, typename Val>
Iter ?nd(Iter b, Iter e, Val x)
{
static_assert(Input_iterator<Iter>(),"?nd(): Iter is not a Forward iterator");
// Rest of code...
}
Run Code Online (Sandbox Code Playgroud)
如果你使用其他方法或者这个方法有问题,请告诉我.