是否可以模拟模板<auto X>?

Xeo*_*Xeo 17 c++ templates type-inference

它有可能吗?我希望它能够启用参数的编译时传递.假设它只是为了方便用户,因为人们可以随时输出真实类型template<class T, T X>,但是对于某些类型,即指向成员函数的指针,即使使用decltype快捷方式,它也非常繁琐.请考虑以下代码:

struct Foo{
  template<class T, T X>
  void bar(){
    // do something with X, compile-time passed
  }
};

struct Baz{
  void bang(){
  }
};

int main(){
  Foo f;
  f.bar<int,5>();
  f.bar<decltype(&Baz::bang),&Baz::bang>();
}
Run Code Online (Sandbox Code Playgroud)

是否有可能将其转换为以下内容?

struct Foo{
  template<auto X>
  void bar(){
    // do something with X, compile-time passed
  }
};

struct Baz{
  void bang(){
  }
};

int main(){
  Foo f;
  f.bar<5>();
  f.bar<&Baz::bang>();
}
Run Code Online (Sandbox Code Playgroud)

GMa*_*ckG 13

更新后:没有.C++中没有这样的功能.最接近的是宏:

#define AUTO_ARG(x) decltype(x), x

f.bar<AUTO_ARG(5)>();
f.bar<AUTO_ARG(&Baz::bang)>();
Run Code Online (Sandbox Code Playgroud)

听起来像你想要一个发电机:

template <typename T>
struct foo
{
    foo(const T&) {} // do whatever
};

template <typename T>
foo<T> make_foo(const T& x)
{
    return foo<T>(x);
}
Run Code Online (Sandbox Code Playgroud)

现在而不是拼写出来:

foo<int>(5);
Run Code Online (Sandbox Code Playgroud)

你可以做:

make_foo(5);
Run Code Online (Sandbox Code Playgroud)

推断出论点.

  • 这在C++ 0x中更有用,你可以使用`auto my_foo(make_foo(5));`而不必完全命名类型`foo <int>`. (4认同)

Tad*_*pec 6

它是在 C++17 中添加的 现在您可以编写

template<auto n> struct B { /* ... */ };
B<5> b1;   // OK: non-type template parameter type is int
B<'a'> b2; // OK: non-type template parameter type is char
Run Code Online (Sandbox Code Playgroud)

请参阅http://en.cppreference.com/w/cpp/language/template_parameters非类型模板参数部分的第4 点