gpt4 book ai didi

c++ - 可变模板参数 : can I pick reference vs value depending on type?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:29:35 24 4
gpt4 key购买 nike

编辑不是Undefined reference to static class member 的拷贝 .该问题探讨了问题的原因(我将在下面解释)。在这里,我正在寻找与该问题的答案中提出的那些不同的解决方案(这意味着更改要使用的 constexpr 变量的声明/定义 -本质上是通过在编译单元中添加定义)。

我创建了一个小的可变参数模板函数 make_string() 来从任意数量的 io-able 参数生成一个 std::string,如下所示。

using std::ostringstream; // just for this example

inline ostringstream&write(ostringstream&ostr, const char*x)
{ if(x) ostr<<x; return ostr; }

template<class T>
inline ostringstream&write(ostringstream&ostr, T const&x)
{ ostr<<x; return ostr; }

inline ostringstream&write(ostringstream&ostr) noexcept
{ return ostr; }

template<class T, class... R>
inline ostringstream&write(ostringstream&ostr, T const&x, R&&... r)
{ return write(write(ostr,x), std::forward<R>(r)...); }

inline std::string make_string(const char*text)
{ return {text?text:""}; }

inline std::string make_string(std::string const&text)
{ return {text}; }

template<typename T>
inline auto make_string(T var) -> decltype(std::to_string(var))
{ return std::to_string(var); }

template<class... Args>
inline std::string make_string(Args&&... args)
{
ostringstream ostr;
write(ostr,std::forward<Args>(args)...);
return std::move(ostr.str());
}

现在,这很好用,可以像这样使用

throw std::runtime_error(make_string("offset=",offset," > max_offset =",
max_offset"));

但是,在打印static constexpr 类成员时出现问题,如

class foo
{
static constexpr int max_offset=some_value;
// ...
void bar(int offset)
{
if(offset > max_offset)
throw std::runtime_error(make_string("offset=",offset," > max_offset=",
max_offset"));
}
};

这会导致链接时出错。原因是 make_string 通过引用获取其所有参数,包括 static constexpr max_offset。因此,链接时需要引用 foo::max_offsetsee also .

如何在不放弃make_string()的想法的情况下避免这个问题? (也许可以用可变参数宏替换可变参数模板,但我认为这是某种回归。)make_string 必须有一种方法可以根据类型按值或引用获取其参数(以便内置类型可以取值)。怎么办?

最佳答案

我不确定编译器是否正确地获取它的 knickers in a bunch jimmies 在这里用 constexpr 的引用沙沙作响。

但是,您也许可以使用 boost 找到出路

  • call_traits<T>::param_type

    定义一个类型,表示将类型 T 的参数传递给函数的“最佳”方式。

(参见 http://www.boost.org/doc/libs/1_55_0/libs/utility/call_traits.htm)。

关于c++ - 可变模板参数 : can I pick reference vs value depending on type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22400980/

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