c++ - 模板 - 以列出的参数为条件

标签 c++ c++11

我该怎么做才能达到评论的要求?

template<typename T1, typename T2=int>
struct foo
{
  //only define foo function if T2 was explictly listed by client
  //(even if it was explictly listed as int)
  //what should be inside "enable_if"?
  foo(T1 t1, T2 t2){}
};

最佳答案

不要将 T2 设置为 int。相反,将其设置为 MagicFlagTypeThatNobodyElseIsSupposedToUse

然后,在您的模板中,创建一个typedef blahblah RealT2,其中blahblah解析为int,如果T2MagicFlagTypeThatNobodyElseIsSupposedToUse,否则为 T2。 (你必须自己实现 blahblah,这是一个非常简单的 traits 类)。

然后在您的代码中使用 RealT2。如果 RealT2T2 相同,则可以检测是否传入了 T2。使用标准技巧根据编译时 bool 条件(通常通过继承)添加/删除方法,或使用 SFINAE 阻止任何匹配您的方法的人。

关于c++ - 模板 - 以列出的参数为条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16968092/

相关文章:

c++ - 通过来自 main() C++ 的多个函数传递指针

c++ - 在C++中围绕另一个圆在圆形路径中制作圆轨道

c++ - std::min/std::max 为 "intrinsic-like"

c++ - 读到 C++ 中的新行进入无限循环

c++ - 使用 gstreamer 时出现 Eclipse 无效参数错误

c++ - Direct3D map 像素黑色

c++ - 从文件中读取十六进制,printf %x 显示前导 ff 值

c++ - 在 STL 中扩充/索引 priority_queue

c++ - 匿名 union 和结构

c++ - 标准库中有子序列算法吗?