【问题标题】:How can I influence the return type of a template class method based on some template argument?如何根据某些模板参数影响模板类方法的返回类型?
【发布时间】:2017-08-18 00:22:30
【问题描述】:

模板类应该有一个返回类型基于模板参数的方法。在这个例子中,我怎样才能让函数返回int(副本)为K=0int&(参考)为K=1

template<typename T, int K>
class someclass
{
public:
    someclass() : member(3) { }
    T giveback() { return member; } // if K=0 should return by T, else return by T&
private:
    T member;
};

int main()
{
    someclass<int,0> x;
    x.giveback();
}

【问题讨论】:

  • 注意,我知道我可以进行模板专业化。但是还有其他方法可以实现吗?
  • 委托其他为你做专业的事情。

标签: c++ templates c++14 metaprogramming


【解决方案1】:

你可以这样做:

typename std::conditional<K, T&, T>::type giveback() { return member; }

如果K 为0,则类型为T,否则为T&amp;

实际上并没有“没有模板专业化”这样的东西,因为std::conditional 是使用模板专业化实现的。使用 std::conditional 只会帮助您本地化模板专业化,而不必复制整个课程的大部分内容。

【讨论】:

  • "...不必复制整个班级的大部分内容。"这就是我的意思。
  • 我觉得值得一提的是还有更简洁的std::conditional_t:std::conditional_t&lt;K, T&amp;, T&gt; giveback() { return member; }
猜你喜欢
  • 2021-12-09
  • 2019-11-10
  • 1970-01-01
  • 2022-01-20
  • 2018-02-21
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多