簡體   English   中英

使用模板特化時的 C++ 語法糖或原型生成技術

[英]C++ syntactic sugar or technique for prototype generation when using template specialization

我想知道生成方法原型的首選 C++ 方式是什么,
什么時候使用模板特化? 我追求的技術
應該與 foo 類方法的數量很好地擴展,見下文。

必須更換復制器的標記塊。
請不要手動或腳本管理代碼片段。
一些額外的小修改(可能在標題中)可能是可能的。

為簡潔起見,模板化類 A 放在 Aint 的 typedef 旁邊。

CRTP 解決方案不受歡迎。 允許使用 C++17(不晚於)。
必須使用 VS2019 最近的 g++ 和 clang++ 進行編譯。

編輯 2020-02-09:
一起刪除標記的塊,
這可以用 Compiler Explorer 的 x64 MSVC 19.14 編譯器很好地編譯。
那么我們這里有 g++ 和 clang++ 的編譯器問題嗎?

// begin of testspec.h
template<class T>
class A
{
public:
    A();
    void foo1();
    void foo2();
    void foo3();
};

typedef A<int> Aint;
// end of testspec.h

// begin of testspec.cpp
#include "testspec.h"

#include <iostream>

/////////////// can this block be simplified? //////////
template<>
void
A<int>::foo1();

template<>
void
A<int>::foo2();

template<>
void
A<int>::foo3();
/////////////// can this block be simplified? //////////

template<>
A<int>::A()
{
    foo1();
    foo2();
    foo3();
    std::cout << "hello world" << std::endl;
}

template<>
void
A<int>::foo1()
{
    std::cout << "foo1" << std::endl;
}

template<>
void
A<int>::foo2()
{
    std::cout << "foo2" << std::endl;
}

template<>
void
A<int>::foo3()
{
    std::cout << "foo3" << std::endl;
}
// end of testspec.cpp

// begin of main.cpp
#include "testspec.h"

int main()
{
    Aint a;
    return 0;
};
// end of main.cpp

假設A的一部分沒有被專門化,那么您試圖通過專門化允許可修改行為的A部分可以通過采用策略模式來實現。

class APolicy {
    template <class, class> friend class A;
    void foo1 ();
    void foo2 ();
    void foo3 ();
};

template <class T, class P = APolicy>
class A {
    void foo1() { P().foo1(); }
    void foo2() { P().foo1(); }
    void foo3() { P().foo1(); }
};

然后不是專門化A<int> ,而是實現策略IntPolicy ,然后實例化A<int, IntPolicy>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM