【问题标题】:Nested template class method syntax嵌套模板类方法语法
【发布时间】:2020-08-21 12:55:10
【问题描述】:

如果我有一个以 T 类型为模板的类 A,并且该类有一个以 U 类型为模板的方法 Foo

template <class T>
class A
{
public:
    template <class U>
    void Foo();
};

要在类之外定义该函数,我需要两个这样的模板语句

template <class T>
template <class U>
void A<T>::Foo() {}            // this compiles

以下不编译

template <class T, class U>
void A<T>::Foo() {}            // this does not compile

有错误

prog.cpp:10:6: error: no declaration matches ‘void A<T>::Foo()’
 void A<T>::Foo() {}
      ^~~~
prog.cpp:6:7: note: candidate is: ‘template<class T> template<class U> void A<T>::Foo()’
  void Foo();
       ^~~
prog.cpp:2:7: note: ‘class A<T>’ defined here
 class A
       ^

有没有更简洁/紧凑的方式来像上面一样在单个语句中定义两种模板类型?

【问题讨论】:

  • 我担心没有其他“紧凑”的方式

标签: c++ templates


【解决方案1】:

C++20:缩写函数模板

有没有更简洁/紧凑的方式来像上面那样在单个语句中定义两种模板类型?

从 C++20 开始,您可以使用 abbreviated function templates,它还允许以更紧凑的方式声明(稍后)定义函数模板。但是,这种方法仅限于可以通过模板实参推导推断出的类型模板参数,因为占位符类型(autoSomeConcept auto)必须出现在缩写函数模板声明的参数列表中。

template <typename T>
struct A {
    void foo(auto);
};

template <typename T>
void A<T>::foo(auto) {}

注意void foo(auto) 等价于template&lt;typename T&gt; void foo(T),因为前者声明了一个函数模板,其中包含一个(发明的)模板参数,对应于单个占位符类型。这意味着允许为同一实体混合使用缩写函数模板语法和经典函数模板语法(例如,使用一种语法声明它,另一种语法定义它):

template <typename T>
struct A {
    template <typename U>
    void foo(U);
};

template <typename T>
void A<T>::foo(auto) {}

template <typename T>
struct B {
    template <typename U>
    void foo(U, auto);
};

template <typename T>
void B<T>::foo(auto, auto) {}

【讨论】:

    猜你喜欢
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多