Special C ++ Return Type Template Specification

This is a continuation of this (more general) question: the previous question . A partial answer to this question is given here: a partial answer to this question .

I am interested in the explicit specialization of return type based on template argument. Although the answer above provides a solution to the problem, I believe that there is a more elegant way to solve the problem using C ++ 11/14 methods:

template<int N> auto getOutputPort2();
template<> auto getOutputPort2<0>();
template<> auto getOutputPort2<1>();

template<>
auto getOutputPort2<0>()
{
    return std::unique_ptr<int>(new int(10));
}

template<>
auto getOutputPort2<1>()
{
    return std::unique_ptr<string>(new string("asdf"));
}

The above code compiles and works as expected using gcc 4.8.3 (with -std = C ++ 0x flag). However, it issues the following warning:

getOutputPort2The function uses a type specifier with autono return type.

, ++ 14. ++ 11? decltype ?


. , . ++ 14? , ?

0
1

-- . , , , f<0>, f<1> .. decltype, decltype .

template <int N>
struct f_impl;

template <int N>
decltype(f_impl<N>::impl()) f()
{ return f_impl<N>::impl(); }

template <> struct f_impl<0> {
  static int impl() { return 1; }
};

template <> struct f_impl<1> {
  static const char *impl() { return " Hello, world!"; }
};

int main() {
  std::puts(f<1>() + f<0>());
}

, :

template <> struct f_impl<1> {
  static const char *impl() { return " Hello, world!"; }
};

-

#define DEFINE_F(N, Result)      \
  template <> struct f_impl<N> { \
    static Result impl();        \
  };                             \
  Result f_impl<N>::impl()

DEFINE_F(1, const char *) {
  return " Hello, world!";
}

, , f_impl ( ) .

+2

Source: https://habr.com/ru/post/1568830/


All Articles