小编Nik*_*o O的帖子

根据 char 的符号性专门化结构模板

template<typename T> void frobnicate()我有一个可以做事的函数。我需要 T 成为几种选择类型之一,并且我需要有关这些类型的一些信息。我通过提供特征来做到这一点:

template<typename T_Raw>
struct FrobnicationTraits
{
        static constexpr bool isValidFrobnicationType = false;
};

template<>
struct FrobnicationTraits<unsigned char>
{
        static constexpr bool isValidFrobnicationType = true;
        static constexpr bool isUnsigned = true;
        static constexpr unsigned char minValue = 0;
        static constexpr unsigned char maxValue = 255;
        //Elided in each specialization: some other values that are needed by frobnicate()
};

template<>
struct FrobnicationTraits<signed char>
{
        static constexpr bool isValidFrobnicationType = true;
        static constexpr bool isUnsigned = false; …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++17

3
推荐指数
1
解决办法
94
查看次数

通过三元运算符决定调用哪个成员函数

foo如果我想在一个对象上调用函数thisThing(用 C# 术语来说,这称为“接收器”,所以我在这里也这样称呼它)并传递参数myStuff,我会这样做:
thisThing.foo(myStuff);
超级简单,没什么奇怪的正在这里进行。

如果我想将参数更改为yourStuffbool 值是否b为 false,我会这样做:
thisThing.foo(b ? myStuff : yourStuff);
同样非常简单,三元运算符的基本使用。

如果我想将接收器更改为otherThingif bis false,我会这样做:
(b ? thisThing : otherThing).foo(myStuff);
有点奇怪,你可能不会经常这样做,但这也没什么疯狂的。

但是如果我想将被调用的函数更改为barif bis false,我该怎么做呢?
我会这样想:
thisThing.(b ? foo : bar)(myStuff);
但是,当然,这是行不通的。

有没有一种简单、美观、高性能的方法来做到这一点,最好不要多余地指定任何东西?
可能需要做出一些妥协,但重点是不必重复接收者和参数。所以以下工作:

if (b)
{
    thisThing.foo(myStuff);
}
else
{
    thisThing.bar(myStuff);
}
Run Code Online (Sandbox Code Playgroud)

但你必须重复接收者和参数。想象一下,thisThingmyStuff是更复杂表达式的占位符。您可能希望首先将它们放入局部变量中,但这会对复制产生影响,并且如果您有很多参数,它就不会很好地发挥作用。

您也许可以将函数指针指向这些成员函数,然后执行类似的操作(b ? pointerToFoo : pointerToBar)(myStuff);,但是处理函数指针往往很混乱(想想函数重载),而且编译器似乎不会正确优化掉它。但我很高兴在这里被证明是错误的。

c++ conditional-operator c++17

1
推荐指数
1
解决办法
409
查看次数

标签 统计

c++ ×2

c++17 ×2

conditional-operator ×1

templates ×1