gpt4 book ai didi

c++ - 如何 static_assert 给定的函数调用表达式是否可以编译?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:34:58 25 4
gpt4 key购买 nike

有没有一种方法可以检查函数调用表达式是否会在编译时进行编译并对其进行 static_assert?还是我应该通过 system() 调用编译器并检查退出代码?

#include <type_traits>

template < typename... Args >
void f(Args && ... args, bool);

template < typename... Args >
void g(Args && ... args);

int main()
{
g(1, 2.0, "hello", false); // compiles
f(1, 2.0, "hello", false); // doesn't compile
// How do I do this?
// static_assert(!does_this_compile(f(1, 2.0, "hello", false)), "As expected");
}

最佳答案

首先将调用结果包装成一个类型:

template<class...Args>
using f_r=decltype(f(std::declval<Args>()...));

现在f_r<int>是调用类型 fint右值。

接下来写这个:

namespace details{
template<template<class...>class Z, class, class...Ts>
struct can_apply:std::false_type{};
template<template<class...>class Z, class...Ts>
struct can_apply<Z,std::void_t<Z<Ts...>>,Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
struct can_apply:details::can_apply<Z,void,Ts...>;

现在使用它:

template<class...Args>
using can_f = can_apply<f_r, Args...>;

这给了我们:

static_assert(!can_f<int, double, decltype("hello"), bool>{}, "As expected");

这只检查早期 错误,基本上是在解析正文之前捕获的错误。 (SFINAE“错误”)以后的错误被允许是致命的和不可检查的。

关于c++ - 如何 static_assert 给定的函数调用表达式是否可以编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38355525/

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