具有using关键字和参数包的C ++模板函数

时间:2018-06-27 10:44:46

标签: c++ templates

// I have an alias like this 
template<typename ... Args>
using msg_formatter = string(const string&, const Args &... );

// and it is returned by a class like this
class logger{
public:
msg_formatter* formatter() const;
};

// then somewhere else I wanna be able to call this
logger log;
log.formatter()("my text: %d", 123);

但这似乎不起作用,有什么主意吗? 非常感谢。

1 个答案:

答案 0 :(得分:2)

由于msg_formatter是模板,因此必须在返回类型中提供模板参数,但是由于您不知道将要传递的类型,因此需要另一种间接方式。如果您使用的是C ++ 14,则可以使用auto返回类型推导从函数中返回一个lambda:

auto formatter() {
  return [](const string&, auto const&...) {/*...*/};
}

如果您拥有operator()来创建自己的结构,并返回该结构。

相关问题