Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ If-constexpr三元运算符_C++ - Fatal编程技术网

C++ If-constexpr三元运算符

C++ If-constexpr三元运算符,c++,C++,我有一个简单的剪报如下: template<typename> struct function_traits; template<typename Rv, typename... Args> struct function_traits<Rv(Args...)> { static constexpr const char _signature[] = {GetTypeChar<Rv>, '(', GetTypeChar<Args&g

我有一个简单的剪报如下:

template<typename>
struct function_traits;

template<typename Rv, typename... Args>
struct function_traits<Rv(Args...)>
{
    static constexpr const char _signature[] = {GetTypeChar<Rv>, '(', GetTypeChar<Args>()..., ')', '\0'};
}
但这似乎被完全忽略了,只有
之后的内容才会被评估。

这样做可能吗?

好吧,起初我认为我可以在单个数组初始化中实现这一点,但是constexpr getter工作得很好。
这就是我的结局:

template<typename Tp>
constexpr void SetParamType(char*& dst)
{
    if constexpr (std::is_pointer_v<Tp>)
    {
        *dst++ = '[';
    }
    *dst++ = GetTypeChar<Tp>();
}

[[nodiscard]]
constexpr auto signature() const
{
    std::array<char, sizeof...(Args) * 2 + 4> out = {0};
    char * ptr = out.data();

    *ptr++ = GetTypeChar<return_type>();
    *ptr++ = '(';
    (SetParamType<Args>(ptr),...);
    *ptr++ = ')';
    *ptr++ = '\0';

    return out;
}
模板
constexpr void SetParamType(char*&dst)
{
如果constexpr(std::is_pointer_v)
{
*dst++='[';
}
*dst++=GetTypeChar();
}
[[nodiscard]]
constexpr自动签名()const
{
std::array out={0};
char*ptr=out.data();
*ptr++=GetTypeChar();
*ptr++='(';
(SetParamType(ptr),…);
*ptr++=')';
*ptr++='\0';
返回;
}

请注意,计算数组的大小以精确匹配所需的长度是明智的(这毕竟不难,但为了简单起见,我现在就不做了)

在函数参数中,数组总是通过指针或引用传递,而不是通过值传递,例如:
int(float,double[])
实际上是
int(float,double*)
,因此在您的示例中,
std::is_array_v
将始终返回
false
。使用
std::is_pointer_v
来输出
*
,而使用
std::is_reference_v
来输出
&
。要检测数组,首先必须检测引用,删除
&/code>vi一个
std::remove_reference_t
,然后
std::is_array_v
可能会对结果类型起作用。@RemyLebeau哦,该死,你说得对!用
更改
is_array_v
是否指针_v
起作用,谢谢。现在还有一个问题,逗号不是作为元素分隔符,而是作为逗号运算符,因此只有考虑了右边。你知道如何避免吗?据我所知没有。我真的不认为你能在一个数组初始化中完成这一点,就像你正在尝试做的那样。你真的需要一个动态字符串而不是。你知道我怎样才能在指针类型后添加*字符,同时保持cons吗texpr ness?我不需要在单个数组初始化中使用它。@RemyLebeau感谢讨论,这使我找到了解决方案(见下面的答案)
template<typename Tp>
constexpr void SetParamType(char*& dst)
{
    if constexpr (std::is_pointer_v<Tp>)
    {
        *dst++ = '[';
    }
    *dst++ = GetTypeChar<Tp>();
}

[[nodiscard]]
constexpr auto signature() const
{
    std::array<char, sizeof...(Args) * 2 + 4> out = {0};
    char * ptr = out.data();

    *ptr++ = GetTypeChar<return_type>();
    *ptr++ = '(';
    (SetParamType<Args>(ptr),...);
    *ptr++ = ')';
    *ptr++ = '\0';

    return out;
}