【问题标题】:template class different return type depends of class parameters模板类不同的返回类型取决于类参数
【发布时间】:2015-10-08 17:52:18
【问题描述】:

我有这样的课:

template<class T>
class A{
   // lots of methods here

   Something get();
};

如果 T 是特定类,我希望 Something get() 变为 const Something &amp;get()

首先我尝试用继承来做,但它太乱了。

我可以这样做吗,无需专门化整个 class A 并且不引入第二个模板。

【问题讨论】:

  • 也许 std::enable_if 在这种情况下会帮助你?某种 SFINAE 解决方案。
  • 您需要使用模板专业化。但是,您可能不必专门化整个 A。您可以在Something get()位于模板化类B中的地方有一个小技巧。您可以专门化它并让A继承它来获取函数的预期形式。

标签: c++ templates c++11 specialization


【解决方案1】:

你只需用一种简单易用的类似英语的语言写下来。

std::conditional<std::is_same<T, SpecificClass>::value, 
                 Something const&, 
                 Something>::type get();

【讨论】:

    【解决方案2】:

    你可以使用std::conditional,就像n.m.解释的那样,或者,如果你需要不同的行为,你可以使用std::enable_if

    struct Something { };
    
    template<typename T>
    class Foo
    {
      Something something;
    public:
      template<typename U = T, typename std::enable_if<!std::is_same<U, float>::value, int>::type = 0> Something get() {
        std::cout << "not specialized called" << std::endl;
        return something;
      }
    
      template<typename U = T, typename std::enable_if<std::is_same<U, float>::value, int>::type = 0> const Something& get() {
        std::cout << "specialized called" << std::endl;
        return something;
      }
    };
    
    
    Something sm1 = Foo<float>().get();
    Something sm2 = Foo<int>().get();
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2012-07-02
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 2022-11-17
      • 2019-12-18
      相关资源
      最近更新 更多