gpt4 book ai didi

c++ - 检查 C++11 中运算符是否存在的最佳方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:39:28 27 4
gpt4 key购买 nike

<分区>

我需要检查给定的类是否有 <<(cls, ostream)运营商定义与否。如果是这样,我希望我的函数使用它来写入 ostringstream ,否则应使用样板代码。

我知道以前有人问过这个问题。但是,我通常会发现自定义解决方案并不总是适用于我的编译器 (clang++)。经过几个小时的搜索,我终于找到了 boost::type_traits。我之前没有看过那里,因为我假设 c++11 已经复制了 boost 具有的特性部门中的所有内容。

对我有用的解决方案是:

template <typename C>
std::string toString(C &instance) {
std::ostringstream out;
out << to_string<C, boost::has_left_shift<C, std::ostream>::value>::convert(ctx);
return out.str();
}

to_string定义为:

template <typename C, bool>
struct to_string {
// will never get called
static std::string convert(LuaContext &ctx) {}
};

template <typename C>
struct to_string<C, true> {
static std::string convert(LuaContext &ctx) {
return "convert(true) called.";
}
};

template <typename C>
struct to_string<C, false> {
static std::string convert(LuaContext &ctx) {
return "convert(false) called.";
}
};

所以我发布这个有两个原因:

  1. 检查这是否是最明智的使用方法,或者看看其他人是否可以提出更好的解决方案(即这个问题更多是出于对方法的好奇,而不是“这行得通吗?”——它已经行得通了对我来说)

  2. 发布此信息可以节省其他人的搜索时间,以防她/他也需要做类似的事情。

  3. 作为一个更普遍的问题——有时特征类似乎返回 std::true_type 或 std::false_type(好吧,至少对于非增强类)。其他时候他们是 bool 值。这种差异是有原因的吗?如果boost:has_left_shift返回类型而不是 bool , 那么我可以只有一个 to_string结构。

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