Let C ++ output the location of the class / namespace, the parameter is defined in

This code compiles without any warnings or errors and is executable.

template<class T>
struct testclass
{
    template<int I>
    class inner {};
    template<int I>
    void f(inner<I> ) {}
};

int main()
{
    testclass<bool> test;
    test.f(testclass<bool>::inner<3>()); // l. 13
    return 0;
}

Now, what I would like to do is omit testclass::on line 13:

test.f(inner<3>());

This does not work. Is there anything I can add to testclass'so that my code works?

Allowed C ++ 11.

+4
source share
3 answers

First of all, a template.

Index Pattern:

template<unsigned... Is> struct indexes {typedef indexes<Is...> type;};
template<unsigned Max, unsigned... Is> struct make_indexes:make_indexes<Max-1, Max-1, Is...> {};
template<unsigned... Is> struct make_indexes<0, Is...>:indexes<Is...> {};

A helper class that allows you to build a proxy server without naming the enclosing class:

template<int I, typename... Args>
struct inner_helper {
  std::tuple<Args...> args;
  template<typename T, unsigned... Is>
  T construct(indexes<Is...>) && {
    return { std::forward<Args>(std::get<Is>(args))... };
  }
  template<typename T>
  T construct() && {
    return std::move(*this).template construct<T>( make_indexes<sizeof...(Args)>() );
  }
};

, , . , inner<3> , :

template<int I, typename... Args>
inner_helper<I, Args...> inner( Args&&... args ) {
  return {std::forward<Args>(args)...};
}

testclass . inner_helper<int, Args...> inner<int> Args..., inner<int>:

template<class T>
struct testclass
{
  template<int I>
  class inner {};
  template<int I>
  void f(inner<I> ) {}
  template<int I, typename... Args>
  void f(inner_helper<I, Args...> h) {
    return f( std::move(h).template construct<inner<I>>() );
  }
};

, :

int main()
{
  testclass<bool> test;
  test.f(inner<3>()); // l. 13
  return 0;
}

, (inner<3>()), inner<3> ( ) f(inner<I>).

, inner<I> inner<I>.

, inner<I> , , . , SCARY ++, ( sortof) .

+3

, , , .

typedef ( - ) . :

template <int I> using inner = testclass::inner<I>;

, testclass.

, - ++ 11

+7

testclass::, inner testclass.

What you can do is change the signature of the function fto make it simpler:

struct testclass
{
    template<int I>
    class inner {};

    template<int I>
    void f1() {
        inner<I> obj;
    }
    template<typename T>
    void f2( T&& )
    {
    }
};

int main()
{
    testclass test;
    test.f1<3>();
    test.f2(testclass::inner<3>());
}
+2
source

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


All Articles