我可以使用define调用运算符<<

Can I use a define to call the operator <<

本文关键字:lt 运算符 调用 可以使 define 我可以      更新时间:2023-10-16

我有一个带有以下重载的类:

template<typename T>
ParamContainer &operator<<(keyValue<T> &couple)
{
  insert(couple.key_, couple.value_);
  return *(this);
}

和keyValue

  template <typename T>
  struct keyValue
  {
    std::string key_;
    T   value_;
    keyValue(std::string key, T &value): key_(key), value_(value){}
  };

我想打电话给我的接线员<lt;像这样:

ParamContainer p;
p << ("value", "content") << ("id", 5);

所以我试图定义这个东西:

#define ParamContainer<<(X, Y) ParamContainer<<keyValue(X, Y)

#define ParamContainer::operator<<(X, Y) ParamContainer<<keyValue(X, Y)

但它没有编译:

src/TemplateEngine.hpp:48:25: warning: ISO C99 requires whitespace after the macro name [enabled by default] src/ControllerPost.cpp: In member function 'virtual void ControllerPost::operator()(boost::cmatch&, http::server3::reply&, boost::container::flat_map<std::basic_string<char>, std::shared_ptr<PostParam> >&)':
src/ControllerPost.cpp:32:19: error: expected unqualified-id before '<<' token 
src/ControllerPost.cpp:32:19: error: 'X' was not declared in this scope
src/ControllerPost.cpp:32:19: note: suggested alternative:
/usr/local/include/boost/function/function_base.hpp:92:13: note: 'boost::detail::function::X'
src/ControllerPost.cpp:32:19: error: 'Y' was not declared in this scope
src/ControllerPost.cpp:32:19: error: expected ';' before 'ParamContainer'
src/ControllerPost.cpp:34:3: error: 'm' was not declared in this scope

来自第32行:

  TemplateEngine::ParamContainer m;
  m << ("name", "value");

如果我不能使用C++符号,我想我会找到另一种方法

函数样式和常量样式预处理器定义的名称都必须是有效的C++标识符。它们不能包含<<符号,所以预处理器不可能实现您的技巧。