1

在模板中我可以这样做:

struct Type_Which_std_cout_MayAccept {};

template <typename T>
struct AAA
{
    AAA(T t) { if constexpr (false) std::cout << t; }
};

int main()
{
    AAA{ Type_Which_std_cout_MayAccept() };
}

哪个工作正常。这就是为什么我为什么认为如果 constexpr 条件为假,编译器将不会尝试评估该语句。所以我希望这会起作用,但事实并非如此。我显然有错误的理解:

struct NoType {};


template <typename T>
struct MemberOrNothing
{
    MemberOrNothing(T arg) : member(arg) {}
    constexpr bool hasMember() { return true; }
    T member;
};
template <>
struct MemberOrNothing<NoType>
{
    MemberOrNothing(NoType) {}
    constexpr bool hasMember() { return false; }
};

template <typename T_MemberOne, typename T_OptionalSecondMember = NoType>
struct OneOrTwoMemberStruct
{
    OneOrTwoMemberStruct(T_MemberOne firstMember, T_OptionalSecondMember optionalSecond = NoType())
        : firstMember(firstMember), secondMember(optionalSecond)    {}


    T_MemberOne firstMember;
    MemberOrNothing<T_OptionalSecondMember> secondMember;
    T_OptionalSecondMember& getSecondMember() { return secondMember.member; }
    constexpr bool hasSecondMember() { return secondMember.hasMember(); }
    
};

int main()
{

      OneOrTwoMemberStruct objWithSecondMember{ 7, 'c' };
      OneOrTwoMemberStruct objWithoutSecondMember{ 7 };

    // Works
    if constexpr (objWithSecondMember.hasSecondMember())
        std::cout << objWithSecondMember.getSecondMember() << '\n';
    
    // Doesn't work, std::cout << doesn't accept a NoType
    if constexpr (false)
        std::cout << objWithoutSecondMember.getSecondMember() << '\n';
} 

在第一个示例中,我可以编写将 T 传递给 cout 的运算符 << 的代码,即使它不接受 T,但是在此示例中,我无法传递 cout 运算符 << 可能接受或不接受的类型?

有人可以解释两者之间的区别吗?

4

0 回答 0