【发布时间】:2017-02-23 04:19:07
【问题描述】:
我正在尝试创建一个模板类,它将实现具有不同签名的回调,具体取决于它是使用一种类型还是两种类型进行实例化。
struct NoIntermediate
{
};
template<typename R, typename I>
struct ParserCallbackSwitch
{
using type = std::function<bool(const std::string &, R&, I&)>;
}
template<typename R, typename I = NoIntermediate>
class OtherClass
{
public:
typedef ParserCallbackSwitch<R, I>::type ParserType;
}
现在我想添加代码,如果在实例化“OtherClass”时未指定我,则 ParserCallbackSwitch 将是:
template<typename R, typename I>
struct ParserCallbackSwitch
{
using type = std::function<bool(const std::string &, R&)>;
}
请注意,在这种情况下 ParserCallbackSwitch::type 是一个只有两个参数的函数。
我希望能够做到以下几点:
OtherClass<int, float> p; // p::ParserType = std::function<bool(std::string &, int &, float &);
OtherClass<int> q; // q::ParserType = std::function<bool(std::string &, int &);
当 I 的类型为 NoIntermediate(即未指定 I)时,我不知道如何部分指定 ParserCallbackSwitch
解决方案:基于以下回复。这是我最终使用的代码。
struct NoIntermediate {};
template<typename R, typename I = NoIntermediate>
struct ParserCallbackSwitch
{
using type = std::function<bool(const std::string &, R&, I&)>;
};
template<typename R>
struct ParserCallbackSwitch<R, NoIntermediate>
{
using type = std::function<bool(const std::string &, R&)>;
};
template<typename R, typename I = NoIntermediate>
class OtherClass
{
public:
typedef ParserCallbackSwitch<R, I>::type ParserType;
}
【问题讨论】:
-
也许你想要parameter pack?