【问题标题】:Is it possible to emulate template<auto X>?是否可以模拟模板<auto X>?
【发布时间】:2011-04-11 22:08:39
【问题描述】:

有可能吗?我希望它能够在编译时传递参数。假设它只是为了用户方便,因为总是可以用template&lt;class T, T X&gt; 输入真实类型,但是对于某些类型,即指向成员函数的指针,即使使用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>();
}

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

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>();
}

【问题讨论】:

  • @GMan:更新,希望现在更有意义。 :)

标签: c++ templates type-inference


【解决方案1】:

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

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

f.bar<AUTO_ARG(5)>();
f.bar<AUTO_ARG(&Baz::bang)>();

听起来你想要一个生成器:

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

template <typename T>
foo<T> make_foo(const T& x)
{
    return foo<T>(x);
}

现在不用拼写:

foo<int>(5);

你可以这样做:

make_foo(5);

推断论证。

【讨论】:

  • 这在 C++0x 中更加有用,您可以在其中使用 auto my_foo(make_foo(5)); 而无需将类型完全命名为 foo&lt;int&gt;
  • 如果将参数传递给函数是一个问题,那么提问者可以直接使用f.bar(5); 并将方法简单地声明为template&lt;typename T&gt;void bar(T &amp;X);。你的make_foo()有什么用?
  • @iammilind:在他澄清之前,这是对他问题的一个老猜测。
  • @iamm:模板参数推导仅适用于函数,不适用于类。
  • @Jonathan.:我认为语言中的很多东西在默认情况下都不起作用,更不用说 auto 扩展为两个单独的模板参数了。
【解决方案2】:

它是在 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

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

【讨论】:

    【解决方案3】:

    这是不可能的。实现的唯一方法是将参数传递给函数

    struct Foo{
      template<class T> void bar(T& X) {}
    };
    

    然后调用函数为,

    f.bar(5);
    f.bar(&Baz::bang);
    

    【讨论】:

      猜你喜欢
      • 2020-08-07
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-07
      • 2018-10-08
      • 2022-12-13
      相关资源
      最近更新 更多